#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()循环三次, 可只准读入两行. 为什么?
Because you entered a newline character after you entered
n
, andcin >> n;
will only be read before the newline, so whengetline(cin, s);
in the loop is executed for the first time, the input aftern
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
Enter two