Reputation: 497
Could you please help me with pinning a problem down in my code?
The program is supposed to ask for the user to enter dog names and finally print the name of the third dog. When Icompile and execute the program, it says that "it stopped working" and windows asks me if I wanna close the program or do something else.
#include<iostream>
#include<cstdlib>
using namespace std;
main()
{
string perros[10];
int i;
for(i=1; i<11; i++)
{
cout<<"Introduce el nombre del perro"<<endl<<i;
cin>>perros[i];
}
cout<<"El nombre del tercer perro es "<<perros[2];
system("pause");
}
Upvotes: 1
Views: 67
Reputation: 53225
You need to start the indexing from zero, not one because that is how C/C++ arrays are indexed. You will overflow the maximum size of the stack object.
So, you would be writing something like this after fixing this issue in your original code:
#include<iostream>
#include<cstdlib>
using namespace std;
main()
{
string perros[10];
int i;
for(i=0; i<10; i++)
{
cout<<"Introduce el nombre del perro"<<endl<<i;
cin>>perros[i];
}
cout<<"El nombre del tercer perro es "<<perros[2];
system("pause");
}
Note that, you also do not use the for loop as it was intended to be used. You can merge the int i;
line into the for loop.
However, a more intelligent and C++'ish solution would be to use a standard algorithm for this, and not very low-level indexing, exactly to avoid such issues.
So, you would be writing something like this:
#include<iostream>
#include<cstdlib>
#include <algorithm>
using namespace std;
void readNextString(string str)
{
cout<<"Introduce el nombre del perro"<<endl;
cin >> str;
}
main()
{
string perros[10];
for_each(perros, perros + 10, readNextString);
cout<<"El nombre del tercer perro es "<<perros[2];
system("pause");
}
Upvotes: 0
Reputation: 2038
You should start start loop from 0 to 9
for(i=0; i<10; i++)
Hope this will remove error...
Upvotes: 1
Reputation: 254751
Array indexes start at zero; so your loop should be
for(i=0; i<10; i++)
Yours tries to write into the 11th element of a 10-element array, corrupting memory and unleashing untold mayhem.
Upvotes: 1