【发布时间】:2011-07-12 06:38:49
【问题描述】:
我正在尝试编写一些东西,将字符串中的所有空格替换为下划线。
到目前为止我所拥有的。
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;
我只会得到第一个词,“你好”。
有人知道解决办法吗?
【问题讨论】: