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