如何在C++代码分词过程中移除所有空格并修正输出格式?
C++代码修正:移除空格生成点分隔分词时消除多余点
问题描述
现有C++代码旨在移除分词间的所有空格,输出以英文点分隔的分词结果,但运行后输出存在多余英文点,与预期不符:
原代码
#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, ' ')) // <-- 需要修复 { cout << tok << "."; // <-- 需要修复 } cout << endl; } return 0; }
预期输出
a.1 b.2 c.3
实际输出
a.1. b....2. c..3.
问题根源
getline(ss, tok, ' ')以单个空格作为分隔符,连续空格会被拆分成多个空的tok,比如"b 2"会被拆成""、""、""、""、"2",每个空字符串都会输出一个点。- 最后一个分词后也会额外输出一个点,导致末尾多一个点。
修正方案
方案一:过滤空token + 控制点的输出时机
先跳过空的token,只在非第一个token前输出点,避免末尾多余点:
#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; bool first = true; while(getline(ss, tok, ' ')) { if (tok.empty()) continue; // 跳过空的token if (!first) { cout << "."; // 非第一个token前输出点 } cout << tok; first = false; } cout << endl; } return 0; }
方案二:利用stringstream默认的空格分隔(更简洁)
stringstream默认以任意空白字符(包括多个连续空格)作为分隔符,直接用>>读取token就能自动跳过所有空格,无需手动处理空token:
#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; bool first = true; while (ss >> tok) // 默认跳过所有空白字符 { if (!first) { cout << "."; } cout << tok; first = false; } cout << endl; } return 0; }
验证结果
两种方案运行后都能得到预期输出:
a.1 b.2 c.3
内容的提问来源于stack exchange,提问作者mahmood
相关产品推荐
相关产品推荐

