c++ - 如何将输入文件中的内容放入两个单独的数组中?
问题描述
对于家庭作业问题,我们分配了一个名为“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
解决方案
这是一种方法:
#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::ws
in的使用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;
}
推荐阅读
- python - 任何类型的棉花糖领域
- javascript - JQuery Append 删除 IE 和 Edge 中的字符
- excel - Excel - 条件格式 =MOD(ROW(),2)=0
- r - RShiny UI.r 中的错误:缺少参数“变量”,没有默认值
- laravel - laravel - 在帮助者或服务提供者之间进行选择
- bootstrap-4 - 古怪的引导菜单切换行为
- oauth-2.0 - JWKS URL 应该由服务提供者还是 OpenID 提供者托管?
- r - 具有成对距离矩阵输出的列名和行名
- xamarin.forms - 添加到我的项目但未引用的 NuGet 包
- mysql - LEFT JOIN 情况下的错误消息,false