![](/img/trans.png)
[英]is it possible to read from a specific character in a line from a file in c++?
[英]C++ read specific range of line from file
我在文件中有以下内容:
A(3#John Brook)
A(2#Allies Frank)
A(1#Lucas Feider)
我想逐行阅读。 首先我想按顺序阅读。 例如,A 比 3 比约翰布鲁克。 一切都很好,直到 3 但我怎么能在没有“#”和“)”的情况下阅读约翰布鲁克作为字符串。
我有一个功能,你可以看看我的代码:
void readFile()
{
ifstream read;
char process;
char index;
string data;
read.open("datas.txt");
while(true)
{
read.get(process);
read.get(index);
// Here, I need to read "John Brook" for first line.
// "Allies Frank" for second line.
// "Lucas Feider" for third line.
}
read.close();
}
首先将您的数据组织成某种结构。
struct Data {
char process;
char index;
std::string data;
};
然后实现能够读取单个项目的功能。 将分隔符读入临时变量,然后检查它们是否包含正确的值。 这是一个假设每个项目都在单行中的示例。
std::istream& operator>>(std::istream& in, Data& d) {
std::string l;
if (std::getline(in, l)) {
std::istringstream in_line{l};
char openParan;
char separator;
if (!std::getline(
in_line >> d.process >> openParan >> d.index >> separator,
d.data, ')') ||
openParan != '(' || separator != '#') {
in.setstate(std::ios::failbit);
}
}
return in;
}
之后休息是快速而简单的。 https://godbolt.org/z/aGYvPeWfW
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.