Alex
Alex

Reputation: 129

printing structs in C++

I'm trying to print 3 attributes from a struct. Why won't they all print? They will print 2 at a time, but not all three together.

Upvotes: 0

Views: 114

Answers (1)

Barmar
Barmar

Reputation: 782717

name has a Carriage Return character at the end. So it's printing

2HP Potion\r10

\r moves the cursor to the beginning of the line, without moving to the next line, so 10 overwrites 2H.

I suspect this is because you read the name from a file that was written on Windows, which uses \r\n as its line break sequence in text files. You should either fix the file using dos2unix, or change the code that reads the file to remove \r characters.

You can remove the \r at the end with:

int last_pos = name.size()-1;
if (last_pos >= 0 && name[last_pos] == '\r') {
    name.pop_back();
}

Upvotes: 3

Related Questions