C++字符串拼接出现部分覆盖问题,求原因及解决方案
问题分析与解决
嘿,我一眼就揪出问题所在了!你的booklist数组里的字符串大概率藏着回车符(\r)——也就是ASCII码为13的控制字符,这就是导致字符串被覆盖的罪魁祸首。
为什么会出现覆盖?
当你把d和e拼接成f后,d末尾的\r会让控制台的输出光标直接跳回到当前行的开头位置。这时候打印f时,"1,2,3,4"就从行首开始输出,自然覆盖了d的前几个字符:比如第一个例子里,"brave new world"带了\r,"1,2,3,4"从行首打印就把"brave"盖掉了,最后变成"1,2,3,4ew world"。
验证问题的方法
你可以给代码加一段打印字符ASCII值的逻辑,确认是不是有\r:
for(int xd = 0 ; xd < 10; xd++) { if(booklist[xd].length() != 0) { string d = string(booklist[xd]); // 新增:打印每个字符的ASCII码 cout << "字符ASCII值:"; for (char c : d) { cout << static_cast<int>(c) << " "; } cout << endl; string e = "1,2,3,4"; string f = d + e; cout << d.length() << endl; cout << d << endl; cout << f.length() << endl; cout << f << endl; } }
如果输出里出现了13,那百分百就是\r在搞鬼。
解决办法
只需要清理掉字符串里的\r就行,给你两种实用方案:
- 去掉字符串中的第一个
\r:
size_t r_pos = d.find('\r'); if (r_pos != string::npos) { d.erase(r_pos); }
- 去掉字符串中所有的
\r(需要提前包含<algorithm>头文件):
#include <algorithm> // ... d.erase(std::remove(d.begin(), d.end(), '\r'), d.end());
把清理逻辑加到string d = string(booklist[xd]);之后,再执行拼接操作,就能得到正常的拼接结果了。
原代码内容:
for(int xd = 0 ; xd < 10; xd++) { if(booklist[xd].length() != 0) { string d = string(booklist[xd]); string e = "1,2,3,4"; string f = d + e; cout << d.length() << endl; cout << d << endl; cout << f.length() << endl; cout << f << endl; } }原运行结果:
16 brave new world 23 1,2,3,4ew world 28 nineteen eighty-four (1984) 35 1,2,3,4n eigh...
内容的提问来源于stack exchange,提问作者Kevin eyeson
相关产品推荐
相关产品推荐

