(c ++)从文本文件中读取

时间:2015-09-24 22:58:17

标签: c++

我制作了这个程序,要求用户输入一些学生的成绩,确定他们是否通过,然后确定通过多少次以及多少次未通过考试。这是我的代码:

#include <iostream>
using namespace std;

int main ()
{
    int passing = 0;
    int failing = 0;

    int mid_grade;
    int final_grade;

    int student = 5;


    while (student > 0)
    {   
        cout << "Enter mid-term grade: ";
        cin >>  mid_grade;

        cout << "Enter final grade: ";
        cin >> final_grade;

        double total_grade = (double)mid_grade*3/10 + (double)final_grade*7/10;;
        cout << "The total grade is: " << total_grade << endl;
        student --;

    if (mid_grade < 4 || final_grade < 4 || total_grade < 10)
        {
//          cout << "Fail." << endl;
            failing++;
        }
    else 
        {
//          cout << "Pass!" << endl;
            passing++;
        }
    }
    cout << passing << " student passed" << endl;
    cout << failing << " student failed" << endl;
    return 0;
}

我现在要做的是告诉我的程序在我制作的文本文件中阅读中期和最终成绩然后计算总成绩(就像我在上面的代码中所做的那样),然后显示成绩屏幕,确定谁通过和未通过考试以及通过/未通过考试的学生总数。 这是我的文本文件的样子:

Mid-term    Final     
8           5
9           6
10          11
15          17
9           20
11          19

2 个答案:

答案 0 :(得分:1)

好吧,这应该有所帮助。我做了一些笔记。您需要在名为grades.txt

的同一目录/ src中创建一个文本文件

应该是这样的

10 9 8 7 4 3 4 5 5 9

你需要改变一些事情。但这应该给你一个良好的起点或你应该去的地方。希望这可以帮助。

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

int main ()
{
    int passing = 0;
    int failing = 0;

    int mid_grade = 0;  //Always initilize your variables!!!
    int final_grade = 0;

    int student = 5;


    //Create a variable to open the file
    ifstream inFile; inFile.open("src\\grades.txt");

    while (student > 0)
    {
        cout << "Enter mid-term grade: ";
        inFile >>  mid_grade;
        cout << mid_grade << endl;

        cout << "Enter final grade: ";
        inFile >> final_grade;
        cout << final_grade << endl;

        cout << "student number" << student << endl; //Notice it goes backwards you have to fix it.
        double total_grade = ((double)mid_grade*3)/10 + ((double)final_grade*7/10);
        cout << "The total grade is: " << total_grade << endl;
        student --;
        cout << endl;

    if (total_grade < 7)
        {
//          cout << "Fail." << endl;
            failing++;
        }
    else
        {
//          cout << "Pass!" << endl;
            passing++;
        }
    }`enter code here`
    cout << passing << " student penter code hereassed" << endl;
    cout << failing << " student failed" << endl;
    return 0;
}

答案 1 :(得分:0)

我读过这个文件,跳过第一行,然后逐行读取其余部分,使用stringtokenizer来获取两个值。