C++ 从文件读取

c++ reading from file

本文关键字:读取 文件 C++      更新时间:2023-10-16

我正在尝试编写一个程序,该程序将从文件中读取整数并显示它们以及运行平均值。我已经编写了代码来执行此操作,当我从中读取的文件采用以下格式时,它可以工作:

5 6 7 8 9
2 3 4 1 2 
4 5 7 8 9 
2 5 6 2 1 
1 2 3 4 5

我正在尝试使相同的程序从包含以下内容的文件中读取(并像以前一样显示整数和平均值):

3 4 5
3
5
7 8 9

但它没有显示,因为我希望它有任何帮助,我们将不胜感激。这是我的代码:

using namespace std;
#include <iostream>
#include <fstream>
#include <string>
int main()
{
    double y = 0, x = 0, value1 = 0;
    string myFileName, myString;
    cout << "please enter the name of the file you wish to open" << "n";
    cin >> myFileName;
    ifstream inFile;
    inFile.open(myFileName.c_str());
    while (!inFile.eof())
    {
        double currentAv;
        while (getline(inFile, myString, (' ')))
        {
            y = y + 1;
            value1 = atof(myString.c_str());
            currentAv = (value1 + x) / y;
            cout << myString << "," << currentAv << endl;
            x = value1 + x;
        }
    }
    inFile.close();
    system("pause");
}

当我输入要打开的第一个文件时,我得到的输出是: 5,5 6,6.5 7,6 .......

我希望第二个文件在输入时显示相同,即整数及其运行平均值,但我得到:

 3
 4
 5
 6
 7
,3

只需修改代码的这一部分...

        double currentAv;
        while (inFile >> value1)
        {
            y = y + 1;
            currentAv = (value1 + x) / y;
            cout << value1 << "," << currentAv << endl;
            x = value1 + x;
        }