2014-11-02 100 views
-2

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

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

我的目标有以下原则: 2.从文件中读取数据。 a。使用嵌套循环。 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; 
} 

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

+1

你得到编译错误或运行时错误? “它说我的变量未定义”是什么意思? – irrelephant 2014-11-02 21:20:01

+0

除非我误解,否则您将'score'添加到'total',而不给'total'一个初始值。 – druckermanly 2014-11-02 21:20:01

+0

如果您不明白您遇到的错误,请考虑发布错误的整个文本,而不是尝试总结它。 – 2014-11-02 21:24:28

回答

0

你正在一个很琐碎的错误: -

你先while循环: -

while (studentCount <= 3) 

在这之后你的第二个while循环

while (studentCount <= 3) 

由于studentCount已经4它不会进入这个循环。

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

studentCount = 1; 
while (studentCount <= 3) 
+0

谢谢你的帮助。我一直盯着这段代码,这些东西一定是逃过了我的眼睛! – 2014-11-02 22:15:56

0

int numStudents, numTests = 4, studentCount = 1, count = 1, test = 1, score = 0, testCount = 1, 

结束时的逗号应该是一个分号。

0

您的第一行int声明不会以';'结尾。 另外,在读取inputFile和while循环之前,应将StudentCount重置为1。

+0

谢谢!不能相信我没有仔细检查。 – 2014-11-02 22:19:44

0

一些我看到的bug: - 1. int的声明,我很惊讶,你的编译器做别无分号没有指出那个错误。 2.您没有重新初始化,第二循环的变种studentcount由于第一循环将其值设置< 3. 3.你有你的总初始化为0(双总= 0;)