簡體   English   中英

逐行處理文件並解析該行以獲取單獨的變量

[英]Processing a file line by line and parsing the line to get separate variables

因此,我是C ++的新手,我正在嘗試獲取一個如下所示的文件:

0 A
1 B
2 C
3 D
4 E

我顯然需要逐行處理此文件,然后在每一行中,我需要從該行中獲取兩個數字,並將它們放在地圖中,其中該數字是節點名稱為字符串的ID#,因此為0將是我地圖中節點A的鍵。

我想我逐行向下,但是那還是有些困難。

這是我所擁有的:

bool read_index(map<long, string> &index_map, string file_name)
{
    //create a file stream for the file to be read
    ifstream index_file(file_name);

    //if file doesn't open then return false
    if(! index_file.is_open())
        return false;

    string line;
    //read file
    while(! index_file.eof())
    {
        getline(index_file,line);
        stringstream ss(line);
        while(ss)
        {
            //process line?
        }
    }

    //file read
    return true;
}

如果字符串中沒有空格,則可以忽略換行符,而僅提取令牌:

void read_index(std::istream & infile, std::map<long, std::string> & index_map)
{
    long n;
    std::string token;

    while (infile >> n >> token) { index_map[n] = std::move(token); }
}

在打開此文件之前,應單獨進行打開文件的錯誤檢查。 否則,您的功能做得太多了。

如果您有任意字符串,其中可能包含空格,則需要使用getline

    for (std::string line; std::getline(infile, line); )
    {
        std::istringstream iss(line);

        long n;
        std::string token;
        if (iss >> n >> std::ws && std::getline(iss, token))
        {
            index_map[n] = std::move(token);
        }
        else
        {
            // unparsable input line
        }
    }

如您所見,基於行的處理的好處是您還可以處理無效行並跳過那些行。 一旦完全無法識別令牌,第一個純粹基於令牌的代碼就會立即停止。

您正在濫用eof() 嘗試類似這樣的方法:

bool read_index(map<long, string> &index_map, string file_name)
{
    //create a file stream for the file to be read
    ifstream index_file(file_name);

    //if file doesn't open then return false
    if(!index_file)
        return false;

    string line;
    //read file
    while(getline(index_file, line))
    {
        stringstream ss(line);
        long n;
        std::string token;

        if (ss >> n >> token)
        {
            //process line
            index_map[n] = token; 
        }
        else
        {
            // error do something
        }
    }

    //file read?
    return !file.fail();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM