我正在尝试编写一些将字符串中的所有空格替换为下划线的东西。
到目前为止我所拥有的。
string space2underscore(string text)
{
for(int i = 0; i < text.length(); i++)
{
if(text[i] == ' ')
text[i] = '_';
}
return text;
}
在大多数情况下,如果我正在做类似的事情,这将起作用。
string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;
那将输出“hello_stackoverflow”,这正是我想要的。
但是,如果我要做类似的事情
string word;
cin >> word;
word = space2underscore(word);
cout << word;
我只会得到第一个词,“你好”。
有人知道解决这个问题吗?