c++ - getline()函数在这个循环中为什么少读一次?
阿神
阿神 2017-04-17 13:21:31
0
1
881
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

void print_vector(vector<int>& v) {
  vector<int>::iterator it;
  for (it = v.begin(); it != v.end(); it ++) {
    printf ("%d ", *it);
  }
}

int main() {
  int n, temp;
  cin >> n;
  string s;
  stringstream ss;
  vector<int> numbers;
  for (int i = 0; i < n; i++) {
    getline(cin, s);
    ss << s << " ";
  }
  while (ss >> temp) {
    numbers.push_back(temp);
  }
  print_vector(numbers);
  return 0;
}

以上代码当输入“3”后, 按理说getline()循环三次, 可只准读入两行. 为什么?

阿神
阿神

闭关修行中......

reply all(1)
PHPzhong

Because you entered a newline character after you entered n, and cin >> n; will only be read before the newline, so when getline(cin, s); in the loop is executed for the first time, the input after n will be The newline character entered is read in, so it feels like one less line has been read.

You can compare the following two different inputs to understand:

Enter one

3
1
2

Enter two

3 0
1
2
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template