需要帮助从文件中获取char和int数据

时间:2015-05-02 05:41:13

标签: c++

我正在编写一个程序,其中包含一个包含广告系列结果的文本文件,需要查找针对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;

}

文本文件

Bailey Y 16 68

Harrison N 17 71

Grant Y 20 75

彼得森N 21 69

许Y 20 79

Bowles Y 15 75

Anderson N 33 64

Nguyen N 16 68

夏普N 14 75

Jones Y 29 75

McMillan N 19 8

Gabriel N 20 62

1 个答案:

答案 0 :(得分:1)

放弃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...
}