I am trying to write something that will replace all the spaces in a string with an underscore.
What I have so far.
string space2underscore(string text)
{
for(int i = 0; i < text.length(); i++)
{
if(text[i] == ' ')
text[i] = '_';
}
return text;
}
For the most part this would work, if I was doing something like.
string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;
That would output “hello_stackoverflow”, which is just what I want.
However if I was to do something like
string word;
cin >> word;
word = space2underscore(word);
cout << word;
I would just get the first word, “hello”.
Does anybody know a fix for this?
The problem is that
cin >> wordis only going to read in the first word. If you want to operate on a whole like at a time, you should usestd::getline.For example:
Also, you may want to check that you actually were able to read a line. You can do that like this:
Finally, as a side note, you could probably write your function in a cleaner way. Personally I would write it like this:
Or for bonus points, use
std::transform!EDIT:
If you happen to be lucky enough to be able to use c++0x features (and I know that’s a big if) you could use lambdas and
std::transform, which results in some very simple code: