需要帮助从文件中获取字符和整数数据
Need help getting char and int data from file
我正在编写一个程序,该程序需要一个包含广告活动结果的文本文件,需要找到 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...
}
相关文章:
- 显示基于用户输入的整数的字符
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 将超出范围的整数分配给有符号字符类型
- 碱基对映射 - 将 argv[i] 移动到整数或字符作为输入
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 输入验证以筛选出字符、字符串和一系列整数
- 字符和整数中 **(ptr+1) 的值差异
- 如何将整数向量值插入字符向量
- 字符到整数数组
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 不能将字符转换为整数吗?
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 有没有办法将字符类型转换为整数?
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- 如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)
- 将矢量的整数内容打印为字符串会导致分割错误
- 如何从文件的输入文本中消除字符/整数