1

I've had problems opening files in C++ since day one, and I'm running into the problem of getting specific files open again. Am I doing something wrong? I've tried this part with and without the ".txt" after it, as well as placing it into the C drive and just trying to get it that way, but it still doesn't work.

Code:

ifstream correctAnswers;
ifstream studentAnswers;

correctAnswers.open("C:\CorrectAnswers");
studentAnswers.open("C:\StudentAnswers");

if (correctAnswers && studentAnswers) {
    for (int i = 0; i < SIZE; i++) {
        correctAnswers >> answerKey[i];
        studentAnswers >> studentKey[i];

    }
}
else {
    cout << "error" << endl;
}

The error part keeps showing, so I'm assuming it means the files haven't opened or the files' contents would be copied into the array.

3 Answers3

2

You'll need double backslashes in your filename strings.

correctAnswers.open("C:\\CorrectAnswers");
studentAnswers.open("C:\\StudentAnswers");
djcouchycouch
  • 12,724
  • 13
  • 69
  • 108
2

A '\' in a C (C++) string introduces an escape sequence. To get an actual '\' you need to escape the escape - i.e. "C:\\CorrectAnswers".

A good compiler (with correct error/warning config) would normally say "Unknown escape sequence \C".

R Sahu
  • 204,454
  • 14
  • 159
  • 270
John3136
  • 28,809
  • 4
  • 51
  • 69
0

Oh my lord. Thank you guys. I have an entire program here that wouldn't work because of that specific part. I also had to add the ".txt" at the end to point it in the right direction. ;)

ifstream correctAnswers;
ifstream studentAnswers;

correctAnswers.open("C:\\CorrectAnswers.txt");
studentAnswers.open("C:\\StudentAnswers.txt");

if (correctAnswers && studentAnswers) {
    for (int i = 0; i < SIZE; i++) {
        correctAnswers >> answerKey[i];
        studentAnswers >> studentKey[i];

    }
}
else {
    cout << "error" << endl;
}