-5

I have problem with combining strings from getline with other ones in cout, i have been searching answers but I couldn't find anyone who had similiar problems. My code is:

file.open ("list.txt");
    getline(file, line);
    int i=0;
    do
    {
        getline(file, line);
        dummyStudent.name = line;
        cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
        students.push_back(dummyStudent);
        i++;
    }
    while(!file.eof());
    file.close();

The output should be:

Is student present?

But instead i get:

 present?udent

and the last iteration of loop shows correct text.

1 Answers1

4

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)

scohe001
  • 13,879
  • 2
  • 28
  • 47