qq_42896313 2021-12-15 16:24 采纳率: 100%
浏览 20
已结题

(C++)从txt文件读取数据失败,显示数据类型不匹配(由eof和fail得出的结论)

在C++primer Plus第六版第六章中的程序运行时,从txt文件读取数据失败,显示数据类型不匹配(由eof和fail得出的结论)
主要问题在程序中标注了

// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream>          // file I/O support
#include <cstdlib>          // support for exit()
const int SIZE = 60;
int main()
{
    using namespace std;
    char filename[SIZE];
    ifstream inFile;        // object for handling file input

    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE); 
    inFile.open(filename);  // associate inFile with a file
    if (!inFile.is_open())  // failed to open file
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        // cin.get();    // keep window open
        exit(EXIT_FAILURE);
    }
    double value;
    double sum = 0.0;
    int count = 0;          // number of items read

    inFile >> value;        // get first value                          //读取不知道为什么不成功
    while (inFile.good())   // while input good and not at EOF
    {
        ++count;            // one more item read
        sum += value;       // calculate running total
        inFile >> value;    // get next value
    }
    if (inFile.eof())
        cout << "End of file reached.\n";
    else if (inFile.fail())
        cout << "Input terminated by data mismatch.\n";
    else
        cout << "Input terminated for unknown reason.\n";
    if (count == 0)
        cout << "No data processed.\n";
    else
    {
        cout << "Items read: " << count << endl;
        cout << "Sum: " << sum << endl;
        cout << "Average: " << sum / count << endl;
    }
    inFile.close();         // finished with the file
    // cin.get();
    return 0;
}
文件中的内容为

15 15 15 15 15 16 16 16 16 16
15 15 16 16 16
15

运行结果及报错内容
Enter name of data file: scores.txt
Input terminated by data mismatch.
No data processed.

跟书中例子程序完全一样,为什么得不出来正确的结果,即:
统计txt文件中数据的数目,求他们的和以及平均值

  • 写回答

3条回答 默认 最新

  • 关注

    问题应该出在你的scores.txt文件上了,你确认一下,文件中数字之间要用空格分隔编码方式也可能导致读取失败
    你新建一个scores.txt文件,用记事本打开,把数据复制粘贴进去保存就可以了。
    我运行了一下代码是没有问题的。

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 12月24日
  • 已采纳回答 12月16日
  • 创建了问题 12月15日

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记