简体   繁体   中英

Why is getline taking one extra line?

why the for loop execute m-1 times instead of m. I have used getline() to enter string instead of cin>> . Here is my code.

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstdio>

using namespace std;

int main() {

    int n;
    int m;
    int a;

    cin >> n >> m;

    int arr[10000];

    for(int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    char s[200];

    ostream_iterator<int> screen(cout," ");

    for(int i = 0; i < m; i++) {
        cin.getline(s,20);
        int p = s[2]-48;
        cout << p << endl;
    }
}

Because this:

cin>>n>>m;

Has not read the end of line character from the first line.

Thus the first time through the loop.

cin.getline(s,20);

Will read an empty line.

PS. Prefer to use the string reading version of getline() . That way you guarantee that you can always read a full line.

After last cin>>arr[i] , there is a newline remaining in the stream. So the new line will be assigned to s at the first iteration in the for loop without your input, so it looks like the for loop only iterates m-1 times. See this link for the explanation and solution.

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