0

I am sure that I am making some obvious mistake. I googled my question but I could not find a similar question; apologies if it is there somewhere. Basically, I just want to complete entries for a series of vectors. The programme compiles, and I can complete the first vector; however, it skips over the second and third vector and the programme ends. I can get it to work if I enter cout << "Something" << endl; between each vector. The code is as follows:

int main()
{
    vector<string> name;
    string temp_name;
    for (unsigned int counter1 = 0; counter1 < 10; ++counter1)
    {
        getline(cin, temp_name);
        name.push_back(temp_name);
    }

    vector<int> int1;
    int temp_int1 = 0;
    for (unsigned int counter2 = 0; counter2 < 10; ++counter2)
    {
        cin >> temp_int1;
        int1.push_back(temp_int1);
    }

    vector<int> int2;
    int temp_int2 = 0;
    for (unsigned int counter3 = 0; counter3 < 10; ++counter3)
    {
        cin >> temp_int2;
        int2.push_back(temp_int2);
    }

    return 0;
}

I was just playing around with code and came across this... I am sure its something obvious, but any help is appreciated!

3 Answers3

0

Well not sure if this is the case, but you are calling push back on a attr1 vector, but probably wanted to call it on the one you created above - int1.

The same is with the second loop.

Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75
  • Thanks for the reply Bartlomiej Lewandowski; unfortunately that was just a typo on my post I changed attr1 and attr2 just to make it clearer they were integer vectors for this post. In the code I tried to compile they all match. My apologies. – user3353490 Feb 25 '14 at 23:08
0

You need to remove the EOL character after you extract the string.

getline(cin, temp_name);
name.push_back(temp_name);

// Add this line
cin.ignore(1);
Lother
  • 1,699
  • 1
  • 12
  • 17
0

It seems that when you start entering the second vector you are entering some data that is not a number. In this case the input stream gets erroneous status and ignores all other input

You can check this assumption by inserting an additional pair of statements

vector<int> int1;
int temp_int1 = 0;
if ( !cin ) cout << "Some error occured" << std::endl;
for (unsigned int counter2 = 0; counter2 < 10; ++counter2)
{
    cin >> temp_int1;
    int1.push_back(temp_int1);
}

vector<int> int2;
int temp_int2 = 0;
if ( !cin ) cout << "Some error occured" << std::endl;
for (unsigned int counter3 = 0; counter3 < 10; ++counter3)
{
    cin >> temp_int2;
    int2.push_back(temp_int2);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks Vlad; this was indeed the case.The upside is I learnt more about how cin works and the importance of writing code to withstand misuse! Many thanks to everyone for the feedback. – user3353490 Feb 27 '14 at 12:18