This question already has answers here:
cin and getline skipping input [duplicate]
(4个答案)
5年前关闭。
我有一个由以下内容组成的文本文件:
我将3设置为int'd'。所有其他行应属于int'b'。但是似乎“b”仍在第一行中计数,将其提取为“d”后变为0。
它输出:
我该怎么做才能解决此问题?先感谢您 :)
换行符仍在输入流中。第一次调用
使用
并确保添加
才能使用
(4个答案)
5年前关闭。
我有一个由以下内容组成的文本文件:
3
7 8 9 7 8
5 7 9 5 7
6 8 7 9 7
我将3设置为int'd'。所有其他行应属于int'b'。但是似乎“b”仍在第一行中计数,将其提取为“d”后变为0。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int b, d;
string line;
ifstream file("File.txt");
if(!file.is_open())
cout << "File failed to open." << endl;
file >> d;
while(getline(file, line))
{
istringstream iss(line);
double v = 0;
while(iss >> b)
v += b;
cout << v / 5 << endl;
}
return 0;
}
它输出:
0
7.8
6.6
7.4
我该怎么做才能解决此问题?先感谢您 :)
最佳答案
后
file >> d;
换行符仍在输入流中。第一次调用
getline
将返回空行。使用
file >> d;
// Ignore the rest of the first line.
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(getline(file,line))
并确保添加
#include <limits>
才能使用
std:numeric_limits
。