c++ - getline()函数在这个循环中为什么少读一次?
阿神
阿神 2017-04-17 13:21:31
0
1
816
#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()循环三次, 可只准读入两行. 为什么?

阿神
阿神

闭关修行中......

Antworte allen(1)
PHPzhong

因为在你输入n之后又输入了换行符,而cin >> n;只会读入到换行之前,所以在第一次执行循环中的getline(cin, s);时,会把输入n之后又输入的那个换行符读入,所以会感觉少读入了一行。

你可以比较一下以下两个不同的输入就能明白了:

输入一

3
1
2

输入二

3 0
1
2
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!