gpt4 book ai didi

c++ - 打开 .dat 文件时遇到问题

转载 作者:行者123 更新时间:2023-11-28 07:33:28 24 4
gpt4 key购买 nike

在尝试打开“test.dat”文件时,很难弄清楚我做错了什么。它似乎正在打开它,但没有读取它以提供输出。该程序应该读取数字的频率。

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;


int main()
{
string fileName;
int aTest;

cout << "Enter a File Name: ";
cin >> fileName;

ifstream inFile (fileName.c_str());
if (! inFile)
{
cout << "!!Error in opening file 'test.dat'"<< endl;
}

vector<int> test(101, 0);
while(inFile >> aTest) {
test[aTest]++;
}

system("pause");
return 0;
}

test.dat文件

75  85   90  100  
60 90 100 85
75 35 60 90
100 90 90 90
60 50 70 85
75 90 90 70

这就是我的输出现在的样子

Enter a File Name: test.dat
Press any key to continue . . .

它应该看起来的样子

Enter file name: test.dat
100: 3
90: 8
85: 3
75: 3
70: 2
60: 3
50: 1
35: 1

最佳答案

您的程序不会尝试打印任何内容,因此没有输出也就不足为奇了。添加一个循环并打印出非零条目:

for (int i = 100; i >= 0; i--)
{
if (test[i])
{
cout << i << ": " << test[i] << endl;
}
}

关于c++ - 打开 .dat 文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17203476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com