我建议使用注释和某种形式的错误捕获。即使它只是显示一条错误消息,以及该错误是什么。试试这个对我有用:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int NUM_ANS = 10;
char answers[NUM_ANS], student[NUM_ANS];
// would recommend: 'ifstream fin;' because its shorter
ifstream correctAnswers;
// open the txt file
// ifstream.open(const char* Filename, std::ios_base::open_mode _Mode);
// use 'ios_base::in' for input, and 'ios_base::out' for output
// it tells the ifstream how to file should be opened. In this case for input.
correctAnswers.open("C:/Users/RCLRC115/Desktop/student.txt", ios_base::in);
// check that the last ifstream operation didn't fail.
if (correctAnswers.fail())
{
// print error message
cout << "ERROR: Could not open file!";
cin.get();
// Return a value other than 0 so you'll know there was an error by looking
// at the output window
// The program '[#] programName.exe: Native' has exited with code 1
return 1;
}
else
{
// print success message
cout << "SUCCESS: File Opened! Reading File..." << '\n';
}
int count = 0;
// 'while (count < NUM_ANS && correctAnswers << answers[count])' is where one error was
// 'while (count < NUM_ANS)' is correct. correctAnswers << answers[count] is telling it to store
// the read characters in answers[count], not checking if the character was read, and valid.
// Basically saying:
// 'while (count < NUM_ANS)' AND 'while (ifstream.good())'
// meaning the input file stream read a character and not the end of file.
while (count < NUM_ANS && correctAnswers.good())
{
// this is where the other error was, it probably wasn't storing anything in answers[count]
// store the values read in answers[count]
correctAnswers >> answers[count];
// increment count so loop will end
count++;
}
for (int i = 0; i < NUM_ANS; i++)
{
// print the value in the command window
cout << answers[i] << endl;
}
// Make sure to close files open with ifstream, ofstream, and iofstream
correctAnswers.close();
// Wait to get input so window doesn't close
cin.get();
// Return 0, program exited normally
return 0;
}