Let me take a guess here. Your file was created or edited on Windows, but you're not using Windows to build/run your code. So instead of newline characters at the end of each line (\n
) you have newlines and carriage returns: \r\n
. However there's no newline (and so no carriage return) on the very last line of the file--so only that one looks good. Am I right?
A carriage return will return the cursor to the beginning of the line. So you read in student\r
and then std::cout
writes Is student
, sees the carriage return and moves the cursor back to the beginning of the line and writes present?
there. Resulting in present?udent
.
Either strip the whitespace from the end of your name
string (with the help of code from https://stackoverflow.com/a/217605/2602718)
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
int main() {
//...
getline(file, line);
dummyStudent.name = line;
rtrim(dummyStudent.name);
cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
//...
Or remove those characters from your file. (After hearing that you're on MacOS, you could remove those characters from the file with something like this: Removing Carriage return on Mac OS X using sed)