Sign in to follow this  

c++ inputing a string with spaces

Recommended Posts

When I Input "hello how are you ?" my output is: hello how are you Why the cin ignores the spaces ? How can I input a string which includes spaces?
	 if(strcmp(msg,"exit")==0) break;


Thanks in advance :)

Share this post

Link to post
Share on other sites

strange, i just wrote this...

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::cin;

int main(int arc, char* argv[])
string message;

cin >> message;

cout << message;

while (1);
return 0;

and typed "hello how are you"

and the output is just...


After stepping through i found that cout is not the problem, but cin is. It only puts the first word into 'message'.

Anyone care to explain why this is?


Share this post

Link to post
Share on other sites
Input string data is "tokenized" by default, i.e. broken at whitespace boundaries, with whitespace getting skipped over. This inherits from the behaviour of the old stdio from C. My best guess is that the IO library was designed to make it easier to write... C compilers. :)

Anyway, what you want is the free function 'getline' in iostream, in the std namespace:

getline(ifstream&, string, {char})

Reads a line from the input stream and sets the string contents to the result. If the character argument is provided, it is treated as the delimiter for the line (default is \n).

The member function version of getline reads into a character array instead. I have no idea why they set things up this way (I smell "backward compatibility" though), it's quite a mess :( Please please use the version that reads into a std::string; i.e. use std::strings. It makes for a much happier Zahlman :)

string msg;
{cout << "\ncmd:" << flush;
getline(cin, msg);
if (msg == "exit") break; // see how much nicer it is

Share this post

Link to post
Share on other sites
Original post by spree
Thanks alot guys :), one more question:
is std::string is backword compatible for functions which want a char * as an input argument ?

Yes. A horrible example which uses printf:

std::string pie = "I like pie.";
printf("%s" , pie.c_str());

Yes, std::string::c_str() returns "const char *". Note that if your string changes, the memory pointed to might very well be moved... so don't do:

const char * str1 = pie.c_str();
pie += " Fnord.";
printf("%s" , str1);

And expect your program to work right. Because it won't.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this