当我逐字符串读取文件时,>>操作得到第一个字符串,但它以“ai»?i”开头。假设第一个字符串是"street",那么它就会变成“«»istreet”。
其他字符串也可以。我尝试了不同的txt文件。结果是一样的。第一个字符串以“ai»i”开头。有什么问题吗?
下面是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int cube(int x){ return (x*x*x);}
int main(){
int maxChar;
int lineLength=0;
int cost=0;
cout<<"Enter the max char per line... : ";
cin>>maxChar;
cout<<endl<<"Max char per line is : "<<maxChar<<endl;
fstream inFile("bla.txt",ios::in);
if (!inFile) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
while(!inFile.eof()) {
string word;
inFile >> word;
cout<<word<<endl;
cout<<word.length()<<endl;
if(word.length()+lineLength<=maxChar){
lineLength +=(word.length()+1);
}
else {
cost+=cube(maxChar-(lineLength-1));
lineLength=(word.length()+1);
}
}
}发布于 2012-05-03 00:13:19
你看到的是一个UTF-8的Byte Order Mark (BOM)。它是由创建该文件的应用程序添加的。
要检测并忽略该标记,您可以尝试此(未测试)函数:
bool SkipBOM(std::istream & in)
{
char test[4] = {0};
in.read(test, 3);
if (strcmp(test, "\xEF\xBB\xBF") == 0)
return true;
in.seekg(0);
return false;
}发布于 2013-06-21 00:58:54
参考上面Mark Ransom的优秀答案,添加此代码将跳过现有流上的BOM (Byte Order Mark)。打开文件后调用。
// Skips the Byte Order Mark (BOM) that defines UTF-8 in some text files.
void SkipBOM(std::ifstream &in)
{
char test[3] = {0};
in.read(test, 3);
if ((unsigned char)test[0] == 0xEF &&
(unsigned char)test[1] == 0xBB &&
(unsigned char)test[2] == 0xBF)
{
return;
}
in.seekg(0);
}要使用以下命令:
ifstream in(path);
SkipBOM(in);
string line;
while (getline(in, line))
{
// Process lines of input here.
}发布于 2012-05-03 00:59:02
这里还有另外两个想法。
如果你是创建这些文件的人,请保存它们的长度,在读取它们时,只需使用以下简单的计算方法删除所有前缀: numOfByesToCut
https://stackoverflow.com/questions/10417613
复制相似问题