在我的程序中,我正在使用 ifstream 读取文本文件以使用 stringstream 读取每一行(使用 getline 进行标记化)打开它;当我得到一个欧洲字符时,比如“è”,它用“├¿”保存这个字符,这按预期工作,因为我使用的是字符串而不是 wstring。 但是当我从 cmd 得到一行(我使用的是 Windows)时,单词“è”在字符串中保存为“è”。我的目标是比较从文件和命令 shell 中读取的字符串,但是如果它们以不同的方式编码,我就会被卡住,因为“è”.compare(“├¿”) 自然是 != 0。我想要两者都“错误”或都正确,因为我的目的不是展示它们,而是计算发生的次数。我正在使用最新版本的 Code::Blocks、MinGW 32 位和 gcc 4.7.1 进行编程
更新(代码)
ifstream file;
stringstream stream;
file.open(path);
while( file ){
while( getline(file,line) ){
it = 1;
stream << line;
if( line.compare("")!=0 ){
while( getline(stream,token,'\t')) {
if( it == 1 ){
ID = atoi( token.c_str() );
}
if( it == 2 ){
word = token;
if( !case_sensitive ){
word = get_lower_case( word );
}
}
if( it == tags_index ){
pos = token;
}
it++;
}
data.push_back(make_row(ID,word,pos));
}
stream.clear();
}
}
这是我用来读取文件的函数的一部分(我有一个结构来存储表格文件的每个条目,我的问题是“word”)。
getline(cin,sentence);
[...]
stringstream stream;
string token;
vector<string> tokens;
stream << sentence;
while( getline(stream,token,' ') ){
tokens.push_back(token);
}
stream.clear();
这就是我在命令 shell 中读取输入流的方式。
最佳答案
您可以尝试设置(注入(inject))语言环境
#include <iostream>
#include <locale>
int main()
{
auto loc = std::locale("it_IT"); // Example: Italian locale
std::cin.imbue(loc); // imbue it to input stream, can use a fstream here
std::cout.imbue(loc); // imbue it to output stream
// rest of the program
}
关于c++ - 如何在 C++ 中正确读取欧洲字符(从文件和命令 shell)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182639/