从文件中读取时无法识别字符
Characters not recognized while reading from file
我在 visual studio 中有以下 c++ 代码来从文件中读取字符。
ifstream infile;
infile.open(argv[1]);
if (infile.fail()) {
cout << "Error reading from file: " << strerror(errno) << endl;
cout << argv[0] << endl;
}
else {
char currentChar;
while (infile.get(currentChar)) {
cout << currentChar << " " << int(currentChar) << endl;
//... do something with currentChar
}
ofstream outfile("output.txt");
outfile << /* output some text based on currentChar */;
}
infile.close();
本例中的文件应主要包含普通 ASCII 字符,但以下两个字符除外:“
和 ”
。
问题是当前形式的代码无法识别这些字符。 cout
字符输出垃圾,它的 int 转换产生一个负数,该负数根据它在文件中出现的位置而不同。
我预感问题出在编码上,因此我尝试根据互联网上的一些示例灌输 infile
,但我似乎没有弄对。 infile.get
到达引号字符时失败,或者问题仍然存在。我缺少哪些细节?
尝试:
while (infile.get(¤tChar, 1))
此外,请确保您通过了 argv[1]
。打印它的值:
cout<<argv[1]<<endl;
您尝试读取的文件可能是 UTF-8 编码的。大多数字符读取良好的原因是因为 UTF-8 向后兼容 ASCII。
为了读取 UTF-8 文件,我将向您推荐这个:http://en.cppreference.com/w/cpp/locale/codecvt_utf8
#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
...
// Write file in UTF-8
std::wofstream wof;
wof.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff,std::generate_header>));
wof.open(L"file.txt");
wof << L"This is a test.";
wof << L"This is another test.";
wof << L"\nThis is the final test.\n";
wof.close();
// Read file in UTF-8
std::wifstream wif(L"file.txt");
wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff, std::consume_header>));
std::wstringstream wss;
wss << wif.rdbuf();
(来自 here)
我在 visual studio 中有以下 c++ 代码来从文件中读取字符。
ifstream infile;
infile.open(argv[1]);
if (infile.fail()) {
cout << "Error reading from file: " << strerror(errno) << endl;
cout << argv[0] << endl;
}
else {
char currentChar;
while (infile.get(currentChar)) {
cout << currentChar << " " << int(currentChar) << endl;
//... do something with currentChar
}
ofstream outfile("output.txt");
outfile << /* output some text based on currentChar */;
}
infile.close();
本例中的文件应主要包含普通 ASCII 字符,但以下两个字符除外:“
和 ”
。
问题是当前形式的代码无法识别这些字符。 cout
字符输出垃圾,它的 int 转换产生一个负数,该负数根据它在文件中出现的位置而不同。
我预感问题出在编码上,因此我尝试根据互联网上的一些示例灌输 infile
,但我似乎没有弄对。 infile.get
到达引号字符时失败,或者问题仍然存在。我缺少哪些细节?
尝试:
while (infile.get(¤tChar, 1))
此外,请确保您通过了 argv[1]
。打印它的值:
cout<<argv[1]<<endl;
您尝试读取的文件可能是 UTF-8 编码的。大多数字符读取良好的原因是因为 UTF-8 向后兼容 ASCII。
为了读取 UTF-8 文件,我将向您推荐这个:http://en.cppreference.com/w/cpp/locale/codecvt_utf8
#include <fstream>
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
...
// Write file in UTF-8
std::wofstream wof;
wof.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff,std::generate_header>));
wof.open(L"file.txt");
wof << L"This is a test.";
wof << L"This is another test.";
wof << L"\nThis is the final test.\n";
wof.close();
// Read file in UTF-8
std::wifstream wif(L"file.txt");
wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff, std::consume_header>));
std::wstringstream wss;
wss << wif.rdbuf();
(来自 here)