C 读取文件,省略了一些信息
C++ Reading file with some information omitted
我有一个像这样构成的文本文件:
G 15324 2353
D 23444
Q 23433 32565
我想将每个信息存储到一个变量中,并将其包含在向量中:
ifstream fin;
fin.open("file.txt");
vector<SomeClass> test;
SomeClass temp;
while (fin >> temp.code >> temp.datapoint>> temp.dataleague)
{
test.push_back(temp);
}
但是,在文件中有时省略了第三个值( temp.dataleague ),并留空。显然,我上面的代码无法正常工作,因为它只会将垃圾放在该字段中。当不确定第三个字段是否包含值时,我该如何执行此操作?
您可以尝试使用:
std::istream::getline
这将使您可以在缓冲区内获取每条线,然后根据需要进行处理。
char buffer[256];
fin.getline(buffer,256);
您可以使用以下方式解析不同的字段:
std::string line = std::string(buffer);
int index = line.find(' ');
if (index>0)
std::cout << "My value is: " << line.substr(0,index);
与您示例:
ifstream fin;
fin.open("file.txt");
vector<SomeClass> test;
SomeClass temp;
char buffer[256];
while (!fin.eof())
{
fin.getline(buffer,256);
auto line = std::string(buffer);
std::vector<std::string> tokens;
int start = 0, end = line.find(' ');
while (end!=-1)
{
tokens.push_back(line.substr(start,end-1));
start = end +1;
end = line.find(' ');
}
if (start<line.size())
tokens.push_back(line.substr(start));
if (tokens.size()==3)
{
test.code = tokens[0];
test.datapoint= tokens[1];
test.dataleague= tokens[2];
test.push_back(temp);
}
}
也许是这样的。阅读整个行,然后在已知的定界符('')上解析。一旦知道了几个物品,您就可以使用Isringstream以预期的方式将它们拉出。
#include <sstream>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ifstream fin("file.txt");
vector<SomeClass> test;
string line;
while (getline(fin, line))
{
istringstream iss(line);
char code = 'X';
int datapoint = 99999, dataleague = 99999;
size_t n = count(line.begin(), line.end(), ' ');
if (n == 0) iss >> code;
else if (n == 1) iss >> code >> datapoint;
else if (n == 2) iss >> code >> datapoint >> dataleague;
SomeClass temp(code, datapoint, dataleague);
test.push_back(temp);
}
return 0;
}
相关文章:
- 如何使用软化工具包从 OPC UA 服务器异步读取操作回调中的数据值响应中获取 NodeId 详细信息
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- Qt读取文本文件的一些信息
- 我正在尝试构建一个简单的程序来从 mysql 数据库中读取信息
- 从C 中读取书籍信息
- 在另一个线程中读取/写入信息
- 从一个二进制文件中读取信息,并写入另一个二进制文件
- 提升信息解析器在读取/写入 INFO 格式文件时删除所有注释
- (C++) 如何从要存储在结构数组中的二进制文件中读取.dat信息?
- 使用正则表达式从文件中读取数据信息
- 从结构化阵列中读取信息
- C ++,当我读取二进制文件时,我得到重复的信息
- 双击编译C++ Unix 可执行文件不会打开现有文件以从中读取信息
- C 读取文件,省略了一些信息
- 无法读取代码页不匹配的文件版本信息
- 如何从相机读取缓冲信息
- 通过将结构信息从二进制文件读取到数组中,然后返回到文件C
- 如何将信息从二进制数据文件读取到结构c 的数组中
- 如何从QT中的连接HID设备中读取信息
- 如何将文本文件中的信息读取到构造函数内部的动态数组中