gpt4 book ai didi

c++ - 如何从文本文件中读取值和数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:24 25 4
gpt4 key购买 nike

我知道如何使用 ifstream 等读取文件。我只是被困在这个任务中,我有一个充满常量的头文件和一个包含 3 个变量(预算、酒店类型、[event1、event2、…、eventn)的文本文件]).

#ifndef CONSTANTS_H_
#define CONSTANTS_H_


const string nameMap[] = { "Opening", "Soccer 1", "Soccer 2", "Soccer 3",
"Track and Field 1", "Track and Field 2", "Track and Field 3",
"Track and Field 4", "Swimming 1", "Swimming 2", "Gymnastics 1",
"Gymnastics 2", "Basketball 1", "Basketball 2", "Closing" };
const int eventPriceMap[] = { 2000, 80, 160, 500, 80, 100, 120, 140, 100, 100, 60, 100,
150, 300, 800 };

const int eventDateMap[] = { 0, 3, 6, 9, 1, 2, 3, 4, 5, 6, 7, 8, 5, 7, 9 };

const int eventQuota[] = {60, 47, 30, 22, 50, 52, 42, 25, 37, 20, 43, 34, 35, 30, 40};

const int hotelPriceMap[] = {160, 210, 320};

const int hotelQuota[] ={20, 25, 30};// per day

const int MAXEVENTS = 10;

const int MAXREQUESTS = 150;

const int NUMBEROFEVENTS = 15;

const int NUMBEROFDAYS = 10;

#endif /* CONSTANTS_H_ */
9020,4[2,0,5,14,10,4,3,13,1]
7805,5[13,3,12,12,0,9,7,10,6,1]
7075,5[3,2,4,9,7,0,1,5,6,14]
7679,4[0,4,14,1,3,12,5,10]
6356,3[7,3]
6874,5[14,0,4,10,9,3]
4715,4[9]
4784,5[11]
4321,3[5,3,8,9]
6469,5[7,6,6,14,12,5,2]
4838,4[1,2]
4103,3[14]
5904,5[5,4,6]
5775,3[10,14,14,8,7,3,4]
7070,4[1,4,6,11,13,3,2,5,14]
4605,3[6,10,1,8,7,3,3]
7484,4[11,5,14,2,6,7,8,1,0]

在另一个文件中,我将如何阅读此文本文档并将其保存到 Budget、hotelType 和 [events] 中。我完全不知道我还在学习 C++,感谢所有帮助过我的人!

编辑:我认为常量头文件对此不是必需的。我的道歉

最佳答案

如果我正确理解您的问题,这里有一个解决方案可以解决您的问题。根据您的文件,您需要三个变量:

  1. 预算,这是一维数组
  2. hotelType,也是一维数组
  3. 事件,可以是二维数组

因此基于此解决方案可能是:

budget[]  = {9020,7805,7075,7679,6356,6874,4715 ...}
hotelType[] = {4,5,5,4,3,5 ...}
events[][] = {{2,0,5,14,10,4,},{13,3,12,12,0,9,7,10,6,1},{3,2,4,9,7,0,1,14} ...}

如果我在正确的轨道上,请告诉我,以便我们可以继续实现......

EDIT

第一个解决方案,使用数组:

#include <iostream>
#include <string>
#include <fstream>

int main()
{
std::ifstream infile("file.txt");
std::string line;
int budget[100], hotelType[100], events[100][100], index = 0;
while (std::getline(infile, line)){
std::string num;
int i = 0;
for( ; i < line.length(); i++){
if(line[i] != ',' && line[i] != '[' && line[i] != ']')
num += line[i];
else{
budget[index] = std::stoi(num);
num = "";
break;
}
}
i++;
hotelType[index] = std::stoi(line.substr(i, 1));
i++; i++;
for(int j = 0; i < line.length(); i++){
if(line[i] != ',' && line[i] != '[' && line[i] != ']')
num += line[i];
else{
events[index][j] = std::stoi(num);
num = "";
j++;
}
}
index++;
}
for(int i = 0; i < index; i++){
std::cout<< i + 1 << "th: ";
std::cout<< "\tBudget : " << budget[i] << std::endl;
std::cout<< "\tHotel Type: " << hotelType[i] << std::endl;
std::cout<< "\tEvents : " << std::endl;
for(int j = 0; j < 5; j++)
std::cout<< "\t\t" << events[i][j] << std::endl;
}
return 0;
}

关于c++ - 如何从文本文件中读取值和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53096630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com