c++ - getline() 函数的问题

标签 c++ getline

我是 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/

相关文章:

c++ - "printf("%s 行的内存漏洞应该是 %s", argv[1]);"被描述为堆栈溢出?

c - 当我将 0 作为 getline 的第二个参数传递时会发生什么?

c++ - 为什么 getline 正在读取我的整个 unicode 文件

c++ - 如何打印出字符串的某一部分

c++ - 使用抽象层次实现数据结构

c++ - 访问二维数组时读取冲突

c++ - 如何在 unordered_map 中使用 lambda 函数作为哈希函数?

c++ - getline() 带有 UNIX 格式化字符的文本

c++ - getline 不适用于 fstream

c++ - 任何在 C++ 流上执行 printf 的库?