从文本文件中读取两列

read two columns from a text file

本文关键字:两列 读取 文本 文件      更新时间:2023-10-16
string dictionary;
ifstream in;
in.open("Q3.dic");
while(!in.eof())
{
    getline(in, dictionary);
    cout << dictionary <<endl;
}

这是我用来读取文本文件的内容,如下所示:

you     vous
today       aujourd'hui
good        bon
good morning    bonjour
afternoon   après-midi
good evening    bonsoir
much        beaucoup
is      est

注意:英语短语与其法语翻译之间用制表符分隔。

我要知道的是,是否可以将每列读取到两个不同的变量?

我试过了:

in >> english >> french;
cout << english << french <<endl;

但我遇到的问题是三个词的行。

std::getline()接受第三个参数 - delim - 分隔符字符,如果将其指定为第一次调用的't'(制表符),则应获得所需的结果:

std::ifstream in("Q3.dic");
for (std::string english, french;
    std::getline(in, english, 't') && std::getline(in, french);
    )
{
    std::cout << "English: " << english << " - French: " << french
        << std::endl;
}

对于那些包含多个制表符的行,您需要修剪字符串,但我声明这超出了这个问题的范围!

输出:

English: you - French:  vous
English: today - French:        aujourd'hui
English: good - French:         bon
English: good morning - French: bonjour
English: afternoon - French: après-midi
English: good evening - French: bonsoir
English: much - French:         beaucoup
English: is - French:   est

我想你想使用类似 std::map<std::string,std::string> 的东西,其中 yo 有一个词作为特定语言的关键(请阅读评论中的解释):

std::map<std::string,std::string> dictionary;
ifstream in;
in.open("Q3.dic");
std::string line;
while(getline(in, line)) { // Read whole lines first ...
    std::istringstream iss(line); // Create an input stream to read your values
    std::string english; // Have variables to receive the input
    std::string french;  // ...
    if(iss >> english >> french) { // Read the input delimted by whitespace chars
        dictionary[english] = french; // Put the entry into the dictionary.
                                      // NOTE: This overwrites existing values 
                                      // for `english` key, if these were seen
                                      // before.
    }
    else {
       // Error ...
    }
}
for(std::map<std::string,std::string>::iterator it = dictionary.begin();
    it != dictionary.end();
    ++it) {
    std::cout << it->first << " = " << it->second << std::endl;
}

请参阅代码的实时工作示例


根据我在代码注释中的注释,您可能已经注意到可能需要处理非唯一english -> french翻译。在某些情况下,字典中的一个english关键字可能具有多个关联的翻译。

你可以克服这一点,要么像这样声明你的字典

std::map<std::string,std::set<std::string>>> dictionary;

std::multi_map<std::string,std::string> dictionary;