[英]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.