首页 > 解决方案 > 如何将输入文件中的内容放入两个单独的数组中?

问题描述

对于家庭作业问题,我们分配了一个名为“options.txt”的输入文件。该文件的内容包含一个选项(任务的总体方案是我们让用户选择一个汽车型号,然后选择他们想要添加到汽车上的不同选项)和每行的价格。有 15 个选项,因此有 15 个价格。我需要将价格和选项放入它们自己单独的数组中,以便稍后在程序中使用它们,但我不确定如何执行此操作。

我最初认为我可以instream >> price; prices[i] = price; i++;为选项做类似的事情。但是大多数选项都有多个单词,所以我认为这不会起作用。

我还没有任何代码可以显示,所以非常感谢任何帮助。

输入文件内容:

5000 Leather Seats
1000 DVD System
800 10 Speakers
1400 Navigation System
500 CarPlay
500 Android Auto
2000 Lane Monitoring
800 3/36 Warranty
999 6/72 Warranty
1500 Dual Climate
225 Body Side Molding
49 Cargo Net
87 Cargo Organizer
700 450W Audio
1000 Heated Seats

标签: c++

解决方案


这是一种方法:

#include <iostream>
#include <fstream>

int main() {
  std::string item;
  double price;

  std::ifstream file{"options.txt"};

  while (file >> price && std::getline(file >> std::ws, item)) {
    std::cout << item << ":" << price << std::endl;
  }

  return 0;
}

注意std::wsin的使用std::getline(file >> std::ws, item)- 需要跳过流中的下一个 ' ' 字符。

您还可以使用std::substr获取整行并拆分它:

#include <iostream>
#include <fstream>

int main() {
  std::string line;

  std::ifstream file{"options.txt"};

  while (std::getline(file, line)) {
    std::string item = line.substr(line.find_first_of(' ', 0) + 1);
    double price = std::stod(line.substr(0, line.find_first_of(' ', 0)));

    std::cout << item << ":" << price << std::endl;
  }

  return 0;
}

推荐阅读