【问题标题】:Reading In Multiple Data types from a .txt file where one of the strings has spaces C++从其中一个字符串有空格的 .txt 文件中读取多种数据类型 C++
【发布时间】:2015-02-22 20:59:58
【问题描述】:

我有一个如下所示的文本文件:

汽车,CN,819481,维修,假,无

汽车,SLSF,46871,商业,真实,孟菲斯

汽车,AOK,156,温柔,真实,旧金山

(逗号实际上是制表符,但我无法让它们在此站点上正确格式化)

我有一个名为 Car 的对象,我正在将代码读入并使用代码底部的输出进行输出。我当前的代码可以读取所有前 5 种数据类型,但是在读取可能有空格的最后一列时遇到问题。我曾尝试使用 getline,但无济于事。

这是我为将 txt 作为输入的函数所拥有的代码

void input()
{
    ifstream inputFile;
    inputFile.open("input.txt",fstream::in);

    if (inputFile.fail())
    {
        cout<<"input failed"<<endl;
        exit(1);
    }

    string type;
    string reportingMark;
    int carNumber;
    string kind;
    bool loaded;
    string destination;

    while(inputFile.peek() != EOF)
    {
        inputFile>>type>>reportingMark>>carNumber>>kind>>loaded;
        while(inputFile.peek() == ' ')
            inputFile.get();
            getline(inputFile, destination);

        Car temp(reportingMark, carNumber, kind, loaded, destination);
        temp.output();
    }

    inputFile.close();
}

【问题讨论】:

  • 您是否尝试过一次读取整行作为字符串,然后解析并提取结果?

标签: c++ types text-files getline


【解决方案1】:

不要使用&gt;&gt;运算符,使用getline

string line;
while (getline(inputFile, line) {
  // split line by tabs or commas
}

分割函数示例:

vector<string> explode(string &str, char separator) {
  vector<string> result;
  string tmp;

  for (int i = 0; i < str.size(); i++) {
    if (str[i] == separator) {
      result.push_back(tmp);
      tmp.clear();
    } else tmp += str[i];
  }

  if (tmp.size() > 0)
    result.push_back(tmp);

  return result;
}

我希望std::vector 对你来说并不难。示例加载代码(而不是while(inputFile.peek() != EOF) { ... }):

string line;
while (getline(inputFile, line) {
  vector<string> data = split(line, '\t');  // Or use ASCII code 9
  if (data.size() != 5) {
    cout << "Invalid line!" << endl;
    continue;
  }

  Car temp(data[0], data[1], stoi(data[2]), data[3], data[4]);
  temp.output();
}

不要复制粘贴此代码,我看到您有未处理的布尔变量等。

【讨论】:

    【解决方案2】:

    STL 函数std::getline 接受分隔符作为第三个参数,这意味着您可以传递\t 来读取制表符分隔的值。对于最后一个值,只需读取它而不指定分隔符,这意味着将调用函数的重载版本,其中分隔符为\n

    一次读取一行,分成标记,转换为所需的数据类型。

    Here 是一个工作示例。不过可以改进。此外,您应该处理std::stoistd::stringint 转换期间抛出的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多