#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()循环三次, 可只准读入两行. 为什么?
PHPz2017-04-17 13:23:31
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