0

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

4

3 回答 3

1

std::getline()接受两个参数:一个流和std::string读取下一行的对象(以及可选的第三个参数,分隔符)。您传递的int是 a 而不是 a std::string

您可能应该使用普通的格式化提取:

if (readFile >> num >> num2 >> num3 >> num4) {
    // extraction succeeded!
}
else {
    // extraction failed; handle the error here
}
于 2010-10-14T15:51:46.263 回答
0

getline读入 std::string,它不能读入ints。就像readFile >> num >> num2 >> num3 >> num4;你已经拥有的那样使用,并删除带有getlines 的行。

另一方面,您不需要在此处显式关闭文件,因为文件流对象的析构函数会为您处理这些问题。

于 2010-10-14T15:51:54.220 回答
0

std::getline 是一个有用的工具,用于读取单行文本或读取特定字符的文本,并将其写入 std::string 以便进一步读取。默认情况下,它使用换行符,即 '\n' 作为分隔符,但您可以更改它。

关于使用流读取多个整数然后输出它们的平均值,为什么不直接读取到文件末尾,因此:

int count = 0, total = 0, num;
while( instr >> num )
{
  ++count;
  total += num;
}

float mean = (count > 0 ) ? total / num : std::numeric_limits<float>::quiet_NaN();
outstr << mean;

你可以把它变成一个函数,使用 istream & instr 和 ostream & outstr

假设现在我们想将其更改为读取多行,每行都有由空格或制表符分隔的数字。在我们的输出中,我们将所有方法都写在自己的行上。

现在做这样的事情:

std::string line;
while( std::getline( bigInStr, line ) )
{
   std::istringstream iss(line);
   outputMean( iss, outstr );
   outstr << '\n';
}

尽管您可能不想实际输出 NaN,而只是在输出中将该行留空。如果必须返回浮点数,则计算平均值的函数可能希望使用 NaN 作为返回值。如果我们想在迭代时计算方差、偏度和峰度,我们可以同时计算。

然后,您将在行上将这些作为多个值输出,并且您必须选择自己的分隔符。我自己的偏好是在这种情况下使用制表符 ('\t')。

_

于 2010-10-14T16:01:14.467 回答