簡體   English   中英

(C ++)從文本文件讀取

[英](c++) reading from a text file

我制定了這個程序,要求用戶輸入某些學生的成績,確定他們是否通過或失敗,然后確定多少通過和哪些考試不及格。 這是我的代碼:

#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

好吧,這應該會有所幫助。 我寫了一些筆記。 您需要在同一目錄/ src中創建一個名為grades.txt的文本文件。

應該看起來像這樣

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;
}

我將讀取文件,跳過第一行,然后使用stringtokenizer逐行讀取其余部分,以使用兩個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM