[英]How to load the content of a tab delimited file into a 2D vector of strings in C++ when data contains spaces?
I have the following code to load the content of a tab separated file into a 2D vector of strings. 我有以下代码将制表符分隔文件的内容加载到字符串的2D向量中。 Problem is that this is code fails if there is any space in the data. 问题是如果数据中有任何空间,这是代码失败。 How can I modify the code to take that into account. 我如何修改代码以考虑到这一点。
const std::size_t columns = 4;
std::string word;
std::size_t count = 0;
std::ifstream in("some_file");
std::vector<std::vector<std::string>> data;
std::vector<std::string> row;
while(in >> word) {
row.push_back(std::move(word));
if(++count % columns == 0) {
data.push_back(std::move(row));
row.clear();
}
}
Use std::getline to get the entire line, then split the line into separate strings based on a tab delimiter. 使用std :: getline获取整行,然后根据制表符分隔符将行拆分为单独的字符串。 Something like this: 像这样:
#include <sstream>
std::string line;
std::vector<std::vector<std::string>> data;
while(std::getline(in, line)) {
std::string phrase;
std::vector<std::string> row;
std::stringstream ss(line);
while(std::getline(ss, phrase, '\t')) {
row.push_back(std::move(phrase));
}
data.push_back(std::move(row));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.