C 读取文件,省略了一些信息

C++ Reading file with some information omitted

本文关键字:信息 读取 文件      更新时间:2023-10-16

我有一个像这样构成的文本文件:

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;
}