c++ - 如何在 C++ 中正确读取欧洲字符(从文件和命令 shell)?

标签 c++ string io ascii

在我的程序中,我正在使用 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/

相关文章:

c++ - 返回在非类型模板化类中定义的 typedef

c++ - C++ 模板类是否为使用的每种指针类型重复代码?

java - String.format() 将数组作为单个参数

java - 一个正则表达式可以(有效地)统治所有这些?

python - 我如何拆分这个字符串?

c - 如何用C多次写入一个文件?

c++ - USB 上的可移植 Eclipse C\C++ 配置 C++ 编译器(无需计算机安装(C 驱动器、PATH 等))

c++ - 如何以编程方式在 Linux 中获取挂载点的源设备?

c - C语言中如何接受带空格的字符串输入

c++ - 为什么这段代码不断打印换行符?