从文本文件C ++读取输入

道格·L。

尝试从我先前在程序中输入的文本文件读取测试成绩时遇到问题。问题是它说我的变量是不确定的,但我想我已经定义了它们。使用“ ofstream”的程序的编写部分可以很好地工作,并为我提供了以文本文件格式设置的输出。

1001 21 22 23 24 
1002 25 26 27 28 
1003 29 30 31 32 

我的目标有以下准则:2.从文件中读取数据。一种。使用嵌套循环。b。外循环将是“ while”循环,内循环将是“ for”循环(4个测验)。

这是我的下面的代码。希望有人可以看到我要去的地方,并指出正确的方向:

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

int main()
{
    int numStudents, numTests = 4, studentCount = 1, count = 1, test = 1, score = 0, testCount = 1, 
    int stuID;
    double average;
    double total;
    ofstream outputFile;
    ifstream inputFile;

    cout << fixed << setprecision(2);

    //Open file scores.txt
    outputFile.open("Scores.txt");

    //Get the number of students
    cout << "How many students? ";
    cin >> numStudents;


    while (studentCount <= 3)
    {
        cout << "Enter Student ID: ";
        cin >> stuID;
        outputFile << stuID << " ";

        for (test = 1; test <= numTests; test++)
        {

            cout << "Enter grade for quiz " << test << ": ";
            cin >> score;
            outputFile << score << " ";
        }
        outputFile << endl;
        studentCount++;

    }

        outputFile.close(); //closes Output File

        inputFile.open("Scores.txt"); //opens Output File


    while (studentCount <= 3)
        {

        for (test = 1; test <= numTests; test++)
        {
            inputFile >> score;
            total += score;
        }

        average = total / numTests;
        inputFile >> stuID;
        cout << "The average for student " << stuID << " is " << average << endl;

        studentCount++;
        }

    inputFile.close(); //closes Input File





    system("pause");
    return 0;
}

感谢您抽出宝贵的时间来帮助我。

拉维

您犯了一个非常琐碎的错误:

您的第一个while循环是:-

while (studentCount <= 3)

在此之后,您的第二个while循环是

while (studentCount <= 3) 

由于studentCount已经是4,因此不会进入此循环。

您需要为第二个循环重新初始化studentCount:

studentCount = 1;
while (studentCount <= 3)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章