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.

1

3 Answers 3

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, " "); 
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Als. Oh my.. thats so fast!! Just posted the question few seconds ago. Could you please see my edited question?
You need to erase as well. std::remove_if deletes nothing from the string.
@Nicol Bolas: Caught me in a edit.Check the updates.
@Nicol: could you post the sample code?
@Als: What is boost fan? Hmm... I just need a quick and simple solution :). Do i need to import anything if i were using remove_if? Where do i put the "erase" if i use the remove_if?
|
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)

1 Comment

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
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.