我在std :: string中给我提供了一个文本,我想使用stringstream进行分析。该文本是以下格式从CSV文件中的行:
旋转; 5; win; 10;断开; 27; 1; 1; 14
我必须创建一个键值对(在地图中(,其键是线的字符串值(ex:" spin"(,而从行中填充了下一个整数值的矢量(ex: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;
}
}