C++ cout overwriting itself while in for loop
Asked Answered
R

1

7

The cout statement in this for loop:

for (vector<Student>::iterator qw = students.begin(); qw != students.end(); ++qw){
    Student a = *qw;
    name = a.getName();
    regno = a.getRegNo();
    std::cout << "Name: "<< name << " Reg Number: " << regno << endl;
}

Is creating some odd behavior, what the cout should print is something like this:

Name: Mike Sanderson Reg Number: 10101

However which it actually prints out it:

Reg Number: 10101on

It would seem to me that after the second part of the cout statement it is going back to the start of the line and overwriting itself, but why? Hope you guys can help me and if you need more info let me know!

Rebirth answered 12/1, 2013 at 16:36 Comment(3)
Student wouldn't happen to have a pointer in it that is allocated dynamic memory while not following the rule of three, would it?Addieaddiego
What type is name? What does a.getName() return? (Put a debug breakpoint right before the cout line and see what's in name and regno.)Sold
@DavidSchwartz yes I should have put that sorry, name is a std::string and a.getName() returns a std.string toRebirth
N
17

This is what the carriage return character does (that is, \r in a string literal). I assume name string has an \r at the end of it. You'll need to figure out how it got there and remove it.

I'm guessing that perhaps you read the names from a file, and that file was created on Windows, which ends lines with \r\n by default. C++ will usually handle the conversion between line endings for you when reading from a text file, but if you're reading the file as a binary file and using \n as a delimiter, you'll have this problem. The \r will be read as though it were part of the line.

Nearby answered 12/1, 2013 at 16:39 Comment(5)
I was thinking it was there from random memory as a consequence of my comment :pAddieaddiego
Thanks I shall have a look, it 'shouldnt' do but stranger things have happenedRebirth
@ZacPowell Did you read the names from a file? Are you on Windows?Nearby
@sftrabbit, Good thinking, that's quite probable.Addieaddiego
@sftrabbit yes I was reading the names from a file and yes I am (Sadly) using Windows, after removing the last character from the name string it works perfectly so I am guessing it was indeed a return character. Thank you I would have spent another 2+ hours pulling hair out looking for thatRebirth

© 2022 - 2024 — McMap. All rights reserved.