Extra newline in input

Started by
4 comments, last by Nytegard 17 years, 6 months ago
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...
Advertisement
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.
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...
Are you using Visual Studio 6?
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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...

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....
Quote:Original post by mako_5
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...

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.

This topic is closed to new replies.

Advertisement