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

时间:2014-11-02 21:16:35

标签: c++ ifstream ofstream

我尝试从我之前在程序中输入的文本文件中读取测试分数时遇到了问题。问题是它说我的变量是未定义的,但我认为我已经定义了它们。程序的写作部分使用" ofstream"完美地工作,并给了我在文本文件中格式化的输出。

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

我的目标有以下准则: 2.读取文件中的数据。 一个。使用嵌套循环。 湾外部循环将是“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;
}

感谢您花时间帮我看看。

4 个答案:

答案 0 :(得分:0)

末尾的逗号
int numStudents, numTests = 4, studentCount = 1, count = 1, test = 1, score = 0, testCount = 1, 

应该是分号。

答案 1 :(得分:0)

你的第一行int声明不会被&#39 ;;&#39;终止。 此外,在读取inputFile和while循环之前,应将StudentCount重置为1。

答案 2 :(得分:0)

你犯了一个非常微不足道的错误: -

你第一次循环是: -

while (studentCount <= 3)

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

while (studentCount <= 3) 

由于studentCount已经是4,因此无法进入此循环。

您需要重新初始化studentCount以进行第二次循环: -

studentCount = 1;
while (studentCount <= 3)

答案 3 :(得分:0)

我看到的一些错误: - 1.在int的声明中没有分号,我很惊讶你的编译器没有指出这个错误。 2.您没有为第二个循环重新初始化var studentcount,因为第一个循环将其值设置为&lt; 3。 3.您必须将总数初始化为0(双总数= 0;)

相关问题