1

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");
}

3 Answers 3

1

You should start start loop from 0 to 9

for(i=0; i<10; i++)

Hope this will remove error...

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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");
}

2 Comments

thanks bro, i dont know a lot of commands yet cos im a 1st grade student haha but yeah i corrected the code and it worked really good, thanks to all
@PacoMeraz: just use the second snippet that I pasted. Do not use low-level indexing, when you actually wish to go through each element without the actual need for the index. If you happen to use C++11, you could even eliminate the readNextString function in favor of lambda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.