如何将文件中的文本解析为两个不同的变量

问题描述 投票:0回答:1

我有一个文本文件,这里是:

a 0.240741
; 0.037037
k 0.0925926
s 0.222222
l 0.0925926
d 0.314815
ЏЌд|.–&Фsнcп—#

我需要将文本的第一部分(字符及其频率)分配给无序 映射,以及其余文本(ЏЌд|.–&Фsнcп—#)到字符串变量。如何做到这一点?

我有一个结构:

struct data_maps {
    unordered_map<char, double> char_prob; 
    unordered_map<char, string> char_haffcode; 
    string haffcode_all; 
    string ascii_char; 
};

代码,用于解析文件并将文本分配给变量

data_maps parsing_file(string text)
{
    data_maps data;
    ifstream file(text);

    char ch;
    double prob;
    streampos currentPosition;
    if (file.is_open()) {
        while (file >> ch >> prob)
        {
            data.char_prob[ch] = prob;
            streampos currentPosition = file.tellg();
        }

        
        file.seekg(currentPosition);

        string temp;
                while (getline(file,temp)) {
                     data.ascii_char += temp;
                }
    }
    else
        cerr << "Error:file have not opened.";
    return data;
}

当我执行此操作时:

data_maps maps;
maps = parsing_file("D:\\HC_test\\testing.cmph");
for (auto pair : maps.char_prob)
{
    cout << pair.first << " " << pair.second << endl;
}   
cout << maps.ascii_char;

我有这个输出:

a 0.240741
; 0.037037
k 0.0925926
s 0.222222
l 0.0925926
d 0.314815
c++ file parsing
1个回答
0
投票

while (file >> ch >> prob)
从文件中读取,直到到达最后一行,无法提取双精度值。从中恢复起来很复杂,因为你已经消耗了角色,但你真正需要的是整行。

改为从文件中读取行。我只提供一个粗略的轮廓,剩下的留给你(你的代码实际上并没有丢失太多):

std::string line;
while(getline(file,line) {

   //attempt to read a character and a float:
   std::stringstream ss{line};
   if(ss >> ch >> prob) {
        // it was successful ... use ch and prob
   } else {
        // it was not.. use line
   }
}

从文件中读取字符串始终会成功,直到到达文件末尾。仅当您想要使用完整的

line
的最后一行时,提取字符和双精度才会失败。

© www.soinside.com 2019 - 2024. All rights reserved.