我是 C++ 的初学者,我是第一次尝试使用 getline() 函数。 当我编写这段代码时,出现了 2 个错误。
这段代码应该做什么? 它应该从 read.txt 中读取 4 个数字,然后计算它以找到平均值并将输出写入 output.txt。
4 个数字(在 read.txt 中)都在单独的行上,如下所示:
6
12
15
19
代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
ifstream readFile;
ofstream sendFile;
readFile.open ("read.txt");
sendFile.open ("output.txt");;
float mean;
int num, num2, num3, num4;
getline(readFile, num), getline(readFile, num2), getline(readFile, num3), getline(readFile, num4);
readFile >> num >> num2 >> num3 >> num4;
sendFile << "1. The mean of " << num << ", " << num2 << ", " << num3 << ", and " << num4 << "is " << (num + num2 + num3 + num4) / 4;
readFile.close();
sendFile.close();
system ("PAUSE") ;
return 0;
}
错误如下: IntelliSense:重载函数“getline”的实例不匹配参数列表 20 IntelliSense:函数调用中的参数太少 20
最佳答案
std::getline()
接受两个参数:一个流和用于读取下一行的 std::string
对象(以及可选的第三个参数,分隔符)。您传递的是 int
而不是 std::string
。
您可能应该使用普通的格式化提取:
if (readFile >> num >> num2 >> num3 >> num4) {
// extraction succeeded!
}
else {
// extraction failed; handle the error here
}
关于c++ - getline() 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3934711/