简体   繁体   中英

Use for loop count being ignored when using cin in C++

I have a for loop set up to take in user input X amount of times based on the number of nodes used for an adjacency list for this depth first search algorithm.

int nodeNum;

cout << "Number of nodes?: " << endl;
cin >> nodeNum;

cout << "Names: " << endl;
for (int i = 0; i < nodeNum; i++)
{
    getline(cin, tempName);

    v.push_back(tempName); //pushing the name of node into a vector
}

When I submit this into the online compiler of my university and GCC, it skips the last input. Example - I put in the number 8, it'll only take 7 nodes. How can I fix this?

The statement cin >> nodeNum reads the integer but leaves the file pointer immediately after the integer, but before the newline.

So the first iteration of the loop reads that newline as the first line. You can see this effect with:

#include <iostream>
using namespace std;

int main(void) {
    int nodeNum;
    string tempName;

    cout << "Number of nodes?\n";
    cin >> nodeNum;

    cout << "Names:\n";
    for (int i = 0; i < nodeNum; i++)
    {
        getline(cin, tempName);
        cout << "[" << tempName << "]\n";
    }

    return 0;
}

with the sample run:

Number of nodes?
2xx
Names:
[xx]
aaa
[aaa]

One way to fix that is to place:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

immediately after the cin >> nodeNum - this clears out the characters until the end of the current line. You need to include the <limits> header file to use that.

Applying that change to the example code above:

#include <iostream>
#include <limits>
using namespace std;

int main(void) {
    int nodeNum;
    string tempName;

    cout << "Number of nodes?\n";
    cin >> nodeNum;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Names:\n";
    for (int i = 0; i < nodeNum; i++)
    {
        getline(cin, tempName);
        cout << "[" << tempName << "]\n";
    }

    return 0;
}

improves the situation markedly:

Number of nodes?
2xx
Names:
aaa
[aaa]
bbb
[bbb]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM