[英]Using getline and istringstream to read from file is producing zeroes
[英]reading from istringstream using getline and maybe strtok somehow?
我想从具有特定格式的流中读取数据,例如:
“数字:name_that_can_contain_spaces:字符串,字符串,字符串...”不带引号,其中...表示我不知道有多少个字符串用逗号分隔,并且字符串前后都可以有空格,但字符串中间不能有空格,我想在新行停止阅读
我只想使用getline()并将每行存储到字符串中,但是如果有strtok(line,“:”,“:”,“,”,“ \\ n”)之类的东西,我不知道如何继续这将为我解析它,或者我必须自己一个字符地解析它
有效行格式的示例是:
54485965:abc abc abc: some string, next string , third string\n
解析结果将是:
int 54485965
string "abc abc abc"
string "some string"
string "next string"
string "third string"
您可以读取带有std::getline
,然后使用std::string::find
和std::string::substr
对其进行拆分。 在下面的代码中,我们从文件data
读取一行,然后查找:
这样,所有内容都变为用std::stoi
解析为int
std::stoi
),然后丢弃第一部分。 类似地,我们用name
来做。 最后,我们使用以,
分隔的字符串填充std::list
。
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <exception>
#include <stdexcept>
struct entry {
std::string name;
int number;
std::list<std::string> others;
};
int main(int argc, char** argv) {
std::ifstream input("data");
std::list<entry> list;
std::string line;
while(std::getline(input, line)) {
entry e;
std::string::size_type i = 0;
/* get number from line */
i = line.find(":");
if(i != std::string::npos) {
e.number = stoi(line.substr(0, i));
line = line.substr(i + 1);
} else {
throw std::runtime_error("error reading file");
}
/* get name from line */
i = line.find(":");
if(i != std::string::npos) {
e.name = line.substr(0, i);
line = line.substr(i + 1);
} else {
throw std::runtime_error("error reading file");
}
/* get other strings */
do {
i = line.find(",");
e.others.push_back(line.substr(0, i));
line = line.substr(i + 1);
} while(i != std::string::npos);
list.push_back(e);
}
/* output data */
for(entry& e : list) {
std::cout << "name: " << e.name << std::endl;
std::cout << "number: " << e.number << std::endl;
std::cout << "others: ";
for(std::string& s : e.others) {
std::cout << s << ",";
}
std::cout << std::endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.