需要帮助从文件中获取字符和整数数据

Need help getting char and int data from file

本文关键字:字符 整数 数据 获取 帮助 文件      更新时间:2023-10-16

我正在编写一个程序,该程序需要一个包含广告活动结果的文本文件,需要找到 4 个不同人口统计数据的广告系列的平均评级。我想我已经弄清楚了这一切,只是在努力从文件中获取数据并进入 char 和 int 变量。我是否需要将其全部读取为字符串,然后进行转换,或者我可以将它们读取到这些变量中吗?

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
//declare vars
ifstream fileIn;
string path;
string name;
char yn;
int age;
double rating;
double rate1 = 0;
double rate1Count = 0;
double avg1 = 0;
double rate2 = 0;
double rate2Count = 0;
double avg2 = 0;
double rate3 = 0;
double rate3Count = 0;
double avg3 = 0;
double rate4 = 0;
double rate4Count = 0;
double avg4 = 0;
double totalAvg = 0;
cout << fixed << showpoint << setprecision(2);
// prompt user
cout << "Please enter a path to the text file with results: ";
// get path
cin >> path;
cout << endl;
// open a file for input
fileIn.open(path);
// error message for bad file
if (!fileIn.is_open()){
cout << "Unable to open file." << endl;
getchar();
getchar();
return 0;
}
// read and echo to screen
cout << ifstream(path);
// restore the file
fileIn.clear();
fileIn.seekg(0);
cout << endl << endl;
// get average for demos
while (!fileIn.eof){
fileIn >> name;
fileIn >> yn;
fileIn >> age;
fileIn >> rating;
if (yn != 121 && age < 18){
rate1 += rating; 
rate1Count++;
}
if (yn == 121 && age < 18){
rate2 += rating;
rate2Count++;
}
if (yn != 121 && age >= 18){
rate3 += rating;
rate3Count++;
}
if (yn == 121 && age >= 18){
rate4 += rating;
rate4Count++;
}
}
avg1 = rate1 / rate1Count;
avg2 = rate2 / rate2Count;
avg3 = rate3 / rate3Count;
avg4 = rate4 / rate4Count;
cout << yn << age << rating;

// pause and exit
getchar();
getchar();
return 0;

}

文本文件

贝利 Y 16 68

哈里森 N 17 71

格兰特 Y 20 75

彼得森 N 21 69

许莹 20 79

鲍尔斯 Y 15 75

安德森 N 33 64

阮 N 16 68

夏普 N 14 75

琼斯 Y 29 75

麦克米兰 N 19 8

加布里埃尔 N 20 62

放弃cout << ifstream(path); ... fileIn.seekg(0);- 这一切都没有帮助。

对于输入,请使用:

while (fileIn >> name >> yn >> age >> rating)
{
...

当获取输入时出现问题时,它将退出 - 无论是由于类型的无效字符(例如读取数字时的字母)还是文件结尾。

我是否需要将其全部读取为字符串,然后进行转换,或者我可以将它们读取到这些变量中吗?

如上所述,您不需要这样做,但是如果您将每个完整的行作为string然后尝试解析出值,则可以为用户提供更高质量的输入验证和错误消息:

std::string line;
for (int line_num = 1; getline(fileIn, line); ++line_num)
{
std::istringstream iss(line);
if (iss >> name >> yn >> age >> rating >> std::ws &&
iss.eof())
...use the values...
else
std::cerr << "bad input on line " << line_num
<< " '" << line << "'n";
// could exit or throw if desired...
}