简体   繁体   English

学习C ++ —从文件中读取数字

[英]Learning c++ — reading numbers from a file

Quick synopsis: I can write the data into the file correctly (I've checked the .txt file and it presents exactly as it should) but all I can read back is the last number inputted. 快速简介:我可以将数据正确写入文件中(我已经检查了.txt文件,它的显示完全正确),但是我能读回的只是最后输入的数字。 So, if the last quiz grade I input is 85, that's all it will read back. 因此,如果我输入的最后一个测验成绩是85,则将全部回读。 (the studentNumber reads back fine.) Thanks all! (studentNumber读得很好。)谢谢大家! Still learning here ... 还在这里学习...

while (answer == 1)
{
   cout << "What is the student ID?\n";
   cin >> studentNumber;
   cout << "\n";
   cout << "How many quizzes did you take?\n";
   cin >> numQuiz;
   outputFile << "\n";
   outputFile << studentNumber << "\n";
   outputFile << "Number of quizzes: " << numQuiz << "\t" "Grades: ";
   for (int quiz = 1; quiz <= numQuiz; quiz++)

   {


      cout << "Please enter the score for quiz " << quiz << "\t";
      cin >> score;
      total += score;
      // cout << "The score is " << score << " .\n"; 
      outputFile <<  score << "\t"; }

   // outputFile <<  total; 
   cout << "Do you have a student's grades to input?\nIf yes, type 1. If no, type 0.\n";
   cin >> answer;
   cin.ignore();


}

outputFile.close(); 
fstream inputFile;



inputFile.open("grades2.txt");
inputFile >> studentNumber;
cout << studentNumber << "\n";

inputFile >> score;
cout << score << "\n";

You are using the wrong operator to read the data back. 您使用了错误的运算符来回读数据。 Instead of 代替

inputFile << studentNumber;

you need to use 你需要使用

inputFile >> studentNumber;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM