读取文件中的所有数据

时间:2019-05-12 21:47:00

标签: c++ file

我正在编写一个程序,以显示来自文本文件的学生成绩报告。我在为学生正确列出课程时遇到问题,因为跳过了第一门课程,并用文件下一行中的第一个字符串替换了该课程。我也只能在文件中显示一位学生的成绩,而不是所有学生的成绩。

我不确定如何解决数据中的跳过过程。我尝试了几种不同的方式来调整开始循环,但是我要么得到了当前的结果,要么只有一个学生连续循环了

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {

    string ID, lastName, firstName;
    char midInt, sex, letterGrade;
    string phoneNum, classLevel, courseName;
    int regCourses, courseCredit;
    double numGrade, totalNumGrade;
    int credits2018, credits2019;
    double cumGPA2018, cumGPA2019;
    int i;
    ofstream out_stream;
    ifstream in_stream;

    in_stream.open("C:/Users/mss3s_000/Desktop/Stud.txt");

    if (in_stream.fail()) {
        cout << "Input file opening fail.\n";
        exit(1);
    }


    if (!in_stream.eof()) { //I think the issue with not reading all the data is with this loop, but I'm not sure.
        while (in_stream >> ID >> lastName >> firstName >> midInt >> phoneNum >> sex >> classLevel >> credits2018 >> cumGPA2018 >> regCourses >> courseName >> courseCredit >> letterGrade) {

             switch (sex) {
                case 'M':
                    /*sex = "Male";*/
                    break;
                case 'F':
                    /*sex = "Female";*/
                    break;
            }

            if (classLevel == "FR")
                classLevel = "Freshman";
            else if (classLevel == "SO")
                classLevel = "Sophomore";
            else if (classLevel == "JR")
                classLevel = "Junior";
            else if (classLevel == "SR")
                classLevel = "Senior";

            if(letterGrade == 'A')
                numGrade = 4.0;
            else if(letterGrade == 'B')
                numGrade = 3.0;
            else if(letterGrade == 'C')
                numGrade = 2.0;
            else if(letterGrade == 'D')
                numGrade = 1.0;
            else if(letterGrade == 'F')
                numGrade = 0.0;

            cout << "**************************************************" << endl;
            cout << "Student ID number: " << ID << endl;
            cout << "Name: " << lastName << ", " << firstName << " " << midInt << endl;
            cout << "Tel: " << phoneNum << endl;
            cout << "Gender: " << sex << endl;
            cout << "Class Level: " << classLevel << endl;


            if (regCourses == 0) {
                cout << "Registration of Spring 2019: " << "No" << endl;
                cout << "**************************************************" << endl;


            }

            cout << "Registration of Spring 2019: " << "Yes" << endl;
            cout << "\n Unofficial Report Card" << endl;
            cout << "COURSE     CREDITS      GRADE" << endl;
            cout << "======     =======     ======" << endl;
            credits2019 = 0;
            cumGPA2019 = 0.0;

            for (i = 1; i <= regCourses; i++) { //I thought this loop would show all the courses but it is skipping the first course
                in_stream >> courseName;
                in_stream >> courseCredit;
                in_stream >> letterGrade;


                if (letterGrade != 'W') {
                    credits2019 += courseCredit;
                    totalNumGrade += (courseCredit * numGrade);
                    cumGPA2019 = totalNumGrade / credits2019;
                }
                cout << courseName << " " << courseCredit << " " << letterGrade << endl;
                out_stream << courseName << " " << courseCredit << " " << letterGrade << endl;
            }

            cout.setf(ios::fixed);
            cout.setf(ios::showpoint);
            cout.precision(2);
            cout << "\nCredits for Spring 2019: " << credits2019 << endl;
            cout << "GPA till Fall 2018: " << cumGPA2018 << endl;
            cout << "Total Credits: " << (credits2018 + credits2019) << endl;
            cout << "New Cumulative GPA: " << ((credits2019 * cumGPA2019) + (credits2018*cumGPA2018)) / (credits2019 + credits2018) << endl;
            cout << "**************************************************\n" << endl;

        }
    }
    in_stream.close();


    return 0;
}

我希望在课程标题下列出所有课程,并在文件中显示所有学生的信息。

1 个答案:

答案 0 :(得分:0)

您可以使用getline()逐行读取文件,并检查返回值以了解是否已到达文件末尾。

我举了一个简单的示例,该示例从文件中读取所有数据并将它们加载到“学生列表”中。

这是您可以执行的操作:

数据文件

name:Bob
sex:Male
age:18
name:Alice
sex:female
age:16

C ++代码

#include <iostream>
#include <fstream>
#include <vector>

struct Student
{
    std::string name;
    std::string sex;
    std::string age;

    void clear()
    {
        name.clear();
        sex.clear();
        age.clear();
    }
};

std::pair <std::string, std::string> breakdown(const std::string & line);

int main()
{
    std::string data_file("../tmp_test/data.txt");
    std::vector <Student> students;

    std::ifstream in_s(data_file);
    if(in_s)
    {
        std::string line;
        Student current;
        while(getline(in_s, line))
        {
            std::pair <std::string, std::string> pair = breakdown(line);
            if(pair.first == "name") // first field
            {
                current.name = pair.second;
            }
            else if(pair.first == "sex")
            {
                current.age = pair.second;
            }
            else if(pair.first == "age") // last field
            {
                current.sex = pair.second;
                students.push_back(current);
                current.clear(); // Not necessary
            }
            else
                std::cout << "Info: Unknown field encountered !" << std::endl;
        }

        in_s.close();
    }
    else
        std::cout << ("Error: Could not open file: " + data_file) << std::endl;

    // Do what you want with the loaded data
    for(Student s : students)
    {
        std::cout << "Name: " << s.name << "\nSex: " << s.sex << "\nAge: " << s.age << "\n";
        std::cout << std::endl;
    }

    return 0;
}

std::pair <std::string, std::string> breakdown(const std::string & line)
{
    bool found(false);
    unsigned int i;
    for(i = 0; !found && (i < line.length()); ++i)
    {
        if(line[i] == ':')
        {
            found = true;
            --i;
        }
    }
    if(found)
        return std::make_pair<std::string, std::string>(line.substr(0, i), line.substr(i+1, line.size()-i));
    else
        return std::make_pair<std::string, std::string>("", "");
}

支出

  

名称:Bob
  性别:18
  年龄:男性

     

名称:Alice
  性别:16
  年龄:女性

对我来说效果很好。
当然,如果数据文件损坏了,我也没有处理,...但这不是重点。我试图使它尽可能简单,只是为了展示它是如何完成的。

我希望它能提供帮助。