【发布时间】:2014-09-16 01:32:08
【问题描述】:
我使用 ifstream 在文件中第一个单词的开头收到 3 个错误字符。
我尝试修剪字符串,但无济于事。
string trim(string in){
string out;
int strBegin = in.find_first_not_of(" \t");
if( strBegin == string::npos)
return "";//nothing
int strEnd = in.find_last_not_of(" \t");
int strRange = strEnd - strBegin + 1;
out = in.substr(strBegin, strRange);
transform(out.begin(), out.end(), out.begin(), ::tolower);
return out;
}
这是我在读取文件中的第一个单词“Hello”时得到的输出。
� i: 0
�� i: 1
�he i: 2
hell i: 3
ello i: 4
llo i: 5
lo i: 6
o i: 7
这是从以下位置打印的:
for(int i=0; i<temp.length(); i++){
cout<<temp.substr(i,i+1)<<" i: "<<i<<endl;
}
txt 文件上的 cat -vg
M-oM-;M-?Hello, world test
文件实际上包含“Hello, World test”作为第一行
【问题讨论】:
-
int strRange = strEnd - strRange + 1;未定义行为(strRange未初始化)。你的意思可能是int strRange = strEnd - strBegin + 1;。 -
谢谢你,但仍然会产生相同的输出。
-
使用十六进制查看器检查文件。我敢打赌,实际上,在实际数据之前的文件中存在“不寻常”的字符。也许是byte-order mark。除此之外,您的代码appears to work
-
你有什么问题?
-
这看起来就像您在不支持 UTF8 的终端上打印某些 UTF8(或其他宽)字符时得到的结果,所以我猜您可能遇到了意外的字符编码问题。