# Extra newline in input

This topic is 4129 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Problem: When I try to get input using getline(istream&,string&) I end up getting an extra newline... Input: "Bob the Dude" What I get: "Bob the Dude\n" What I want: "Bob the Dude" When I use cin >> input instead, I end up getting the first word just fine... (but I want the whole line, so this test doesn't help me...) Am I wrong in thinking that getline ignores the trailing newline? Here's what I'm trying:
// renames a character
class RenameScript : public Script
{
void run(VirtualMachine& vm_)
{
std::string input = "";
std::cout << "Renaming \"" << vm_.getCharacter()->getName() << "\"" << std::endl;
std::cout << "New name: ";
getline(std::cin,input,'\n');
// renames character using setName(const string& name_)
vm_.getCharacter()->setName(input);
input = vm_.getCharacter()->getName();
std::cout << "Renamed to \"" << input << "\"" << std::endl;

}
};


In case people think this looks weird, I'm playing with my own scripting language a little before I learn Lua...

##### Share on other sites
Why don't you just erase the last character like so:
input.erase( input.end( ) - 1 );

That will just remove the last character from the input string. Also note that passing the newline character to getline as the delimiter is not going to accomplish anything. The newline character is the default anyway.

Hope that helps.

##### Share on other sites
Thanks, I'll use that for now. I think there might be a problem somewhere else that's messing it up, but haven't found it yet...

##### Share on other sites
Are you using Visual Studio 6?

##### Share on other sites
Actually, I'm using Eclipse with C++ and have found the problem. When running console programs it uses '\r' and not '\n' for newlines for some weird reason...

getline(cin,input)
which uses '\n',
getline(cin,input,'\r')
fixes the problem for anyone else with this issue.

My question is if this will cause a problem when running outside of the IDE. I would test it but I need first to figure out how to make executables from Eclipse....

##### Share on other sites
Quote:
 Original post by mako_5Actually, I'm using Eclipse with C++ and have found the problem. When running console programs it uses '\r' and not '\n' for newlines for some weird reason...Instead of getline(cin,input) which uses '\n', getline(cin,input,'\r') fixes the problem for anyone else with this issue.My question is if this will cause a problem when running outside of the IDE. I would test it but I need first to figure out how to make executables from Eclipse....

On Windows, no. On other systems, this causes a huge problem, because other systems don't use a carriage return, only linefeeds. Try useing getline without the delimeter.