1

Possible Duplicate:
Remove spaces from std::string in C++

I am starting to learn cpp. Hope you guys can help me. Right now, I am having a problem with strings. I get input from the user and want to ignore the white space and combine the string. Here it is:

getline(cin, userInput);

If user input is: Hello my name is

I want to combine to: Hellomynameis

Is there a quick way to do that. Your help will be much appreciated. Thanks.

EDIT:

And, for another case: if the user input is: keyword -a argument1 argument2 argument3

How do I separate the words, because I want to check what are the "keyword", "option", and the arguments.

Community
  • 1
  • 1
georgie
  • 13
  • 2
  • "whitespace" != "spaces". But [the top answer] (http://stackoverflow.com/questions/83439/remove-spaces-from-stdstring-in-c#83538) there does answer this question. – MSalters Aug 09 '11 at 08:16

3 Answers3

4

You can use:

remove_if(str.begin(), str.end(), ::isspace); 

The algorithm only changes the values and not the container contained values, So you need to call string::erase to actually modify the length of the container after calling remove_if.

str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); 

or if you are a Boost Fan, You can simple use:

erase_all(str, " "); 
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Use a istringstream if you just want to separate words:

istringstream iss(userInput)
iss >> blah1 >> blah2 ...

blah1 can be any type. If blah1 is a float, for example, then the iss >> blah1 will try to convert the word to a float (like the C function atof).

If you want to do argument parsing, getopt library is probably what you are looking for. It's what drives the argument parsing for most of the gnu command line utilities (like ls)

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
  • Hi @Foo. Hmm... "iss >> blah1 >> blah2", means there is 2 string input from user separated by space? How do I determine how many arguments the user input? I am thinking of doing some validation, like if user enter more than 5 arguments, then I will prompt error message – georgie Aug 09 '11 at 07:06
0

For getting rid of the space what @Als suggested is right.

For parsing the command line arguments: You can probably use a library i.e.

boost::program_options(http://www.boost.org/doc/libs/1_47_0/doc/html/program_options.html),

or getopt

or libargh(http://bisqwit.iki.fi/source/libargh.html)

A. K.
  • 34,395
  • 15
  • 52
  • 89