簡體   English   中英

如何確定文本中的最后一個字符串值

[英]How to determine last string value in a text

我在std :: string中給出了要使用stringstream分析的文本。 文字是csv文件中的一行,格式如下:

旋轉; 5;獲勝; 10;停止位置; 27; 1; 14

我必須創建一個鍵值對(在地圖中),該鍵是行中的字符串值(例如:“ SPIN”),值是由行中的下一個整數值填充的向量(例如:5)。 (KVP:{“ SPIN”,{5}})。

問題是我不知道如何確定該行的最后一個字符串值(在此示例中為“ STOPPOSITIONS”)。

當我在下一次迭代中獲得單詞“ STOPPOSITIONS”時,變量單詞更改為“ 1”,這是錯誤的,因為我應該創建以下kvp(KVP:{“ STOPPOSITIONS”,{27,1,14}})。

為了找到一行的最后一個字符串值,我應該解決什么問題?

這是我正在使用的代碼:

std::map<std::string, std::vector<uint64_t>> CsvReader::readAllKvp()
{
    if (!_ifs->is_open())
    {
        _ifs->open(_fileName);
    }

    std::map<std::string, std::vector<uint64_t>> result;

    std::string  line;
    std::string word;
    uint64_t val;

    while(getline(*_ifs,line,'\n') >> std::ws)
    {
        /* do stuff with word */
        std::istringstream ss(line);

        while(getline(ss, word, ';') >> std::ws)
        {
            //no more strings found
            if(word == "")
            {
                //read all integers at the end of the line and put them
                //in the map at the last key added (in our case: STOPPOSITIONS)
                while(ss >> val)
                {
                    result[result.rbegin()->first].push_back(val);
                }
                break;
            }

            if (result.find(word) == result.end()) //word not found in map
            {
                std::vector<uint64_t> newV;
                result.insert(
                        std::pair<std::string, std::vector<uint64_t>>(word, newV));
            }

            ss >> val;
            result[word].push_back(val);

            ss.ignore(std::numeric_limits<std::streamsize>::max(),';');
        }

    }

    _ifs->close();

    return result;
}

我舉了我建議的方法的一個例子。 它只讀取一行,但是添加另一個外部循環並處理文件的所有行是一個簡單的任務。

#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <vector>

using std::cout;
using std::endl;

std::map<std::string, std::vector<uint64_t>> readAllKvp()
{
    std::string str = "SPIN;5;WIN;10;STOPPOSITIONS;27;1;14";
    std::stringstream ss(str); // Emulating input from file

    std::map<std::string, std::vector<uint64_t>> result;

    std::string word;
    std::string last_string;
    uint64_t val;

    while(getline(ss >> std::ws, word, ';') >> std::ws)
    {
        try {
            val = std::stoi(word);

            if(!last_string.empty())
                result[last_string].push_back(val);
        } catch (std::invalid_argument&) {
            last_string = word;
        }
    }

    return result;
}

int main() {
    auto map = readAllKvp();

    for (auto& m : map) {
        cout << m.first << ": ";

        for (auto v : m.second)
            cout << v << ' ';

        cout << endl;
    }
}

暫無
暫無

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

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