我正在尝试编写一个程序,在 C++ 中使用基于范围的 for 循环来消除空格。例如,如果输入是“你叫什么名字?” ,输出应该是“你叫什么名字?”然而,当我运行下面的代码时,它给出的输出是“Whatisyourname?me?”,这是为什么呢?
int main()
{
string s = "What is your name?";
int write_index = 0;
for (const char &c : s)
{
if (c != ' ')
{
s[write_index++] = c;
}
}
cout << s << endl;
system("pause");
}
最佳答案
在循环后添加如下语句
s.erase( write_index );
或
s.resize( write_index );
从字符串中删除多余的字符。
此类任务的一般方法如下
#include <algorithm>
#include <string>
//...
s.erase( std::remove( s.begin(), s.end(), ' ' ), s.end() );
关于c++ - 在 C++ 中使用基于范围的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480812/