如何删除以下代码中标记之间的所有空格?
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s[3] = {"a 1", "b 2", "c 3"};
for (int i = 0; i < 3; i++) {
stringstream ss(s[i]);
string tok;
while(getline(ss, tok, ' ')) // <-- need to fix
{
cout << tok << "."; // <-- need to fix
}
cout << endl;
}
return 0;
}
预期输出为
a.1
b.2
c.3
但是代码会生成
a.1.
b....2.
c..3.
3条答案
按热度按时间20jt8wwn1#
您可以使用来自流的格式化输入,而不是
std::getline
。默认情况下,格式化输入跳过空格:输出:
Demo
oalqel3c2#
您可以使用
std::regex_replace
来实现这一点,除非有特殊的原因需要使用stringstream。Output
um6iljoc3#
你可以用我之前写的split函数来实现。