The problem is that cin >> wordonly the first word will be read. If you want to work as a unit, you must use std::getline.
For instance:
std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;
In addition, you can check if you were really able to read the line. You can do it like this:
std::string s;
if(std::getline(std::cin, s)) {
s = space2underscore(s);
std::cout << s << std::endl;
}
, , , . :
std::string space2underscore(std::string text) {
for(std::string::iterator it = text.begin(); it != text.end(); ++it) {
if(*it == ' ') {
*it = '_';
}
}
return text;
}
std::transform!
EDIT:
++ 0x ( , if), lambdas std::transform, :
std::string s = "hello stackoverflow";
std::transform(s.begin(), s.end(), s.begin(), [](char ch) {
return ch == ' ' ? '_' : ch;
});
std::cout << s << std::endl;