0

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;
    }
}
Casey
  • 10,297
  • 11
  • 59
  • 88

2 Answers2

2

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
1

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.

Community
  • 1
  • 1
jfly
  • 7,715
  • 3
  • 35
  • 65