У меня возникли проблемы с моим школьным проектом, поэтому я хотел бы помочь найти решение, а не просто опубликовать его. Допустим, входной файл (input1.txt) будет выглядеть так:
Threshold:1
Infectious Period:2
Display:2
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,i,i,s,s,s,s
s,s,s,s,i,i,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
s,s,s,s,s,s,s,s,s,s
Мне нужно получить Порог, Инфекционный Период и Дисплей и сохранить их где-нибудь, а массив / вектор сохранить остальные. Я подумал, что лучше всего скопировать файл во временный файл, а затем использовать его для создания вектора. Мне удалось создать вектор, но у меня проблемы с получением нужных мне значений. Вот мой код:
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
std::vector<std::string> civs;
std::string fileName;
std::ifstream input;
int susceptible = 0;
int infectious = 0;
int recovered = 0;
int vaccinated = 0;
int days = 0;
void getFile()
{
std::string fileName;
std::string line;
std::cout << "Input the file name: "; // Gets the file from the user
std::cin >> fileName;
std::cout << std::endl;
const char *Fname = fileName.c_str();
std::ifstream iFile; //Input output file stream objects
std::ofstream oFile;
iFile.open(Fname); //Opens the user's set input file
if (iFile.fail()) //Checks for an error in opening file then exits program after giving error message
{
std::cerr << "Error opening file" << std::endl;
}
oFile.open("tempFile.txt"); //Opens temporary interim file to process incoming data
while (std::getline(iFile, line, ',')) //Writes out all values separated by ',', leaving all int. Values are left in even numbered lines
{
oFile << line << std::endl;
}
oFile.close();
iFile.close();
}
int main()
{
getFile();
std::ifstream iFile; //Input output file stream objects
std::ofstream oFile;
std::string line;
iFile.open("tempFile.txt");
int lineCount = 0; //Counter used to ensure only even lines are saved into vector
std::vector <std::string> tempStrings;
while (std::getline(iFile, line, ',')) //Places all lines that contain data (even lines) into a string vector for later processing
{
tempStrings.push_back(line);
lineCount++;
}
iFile.close();
for (std::vector<std::string>::const_iterator iter = tempStrings.begin(); iter != tempStrings.end(); ++iter)
std::cout << *iter << ' ';
return 0;
}
Он создает временный файл справа, но первый элемент вектора (tempStrings [0]) выглядит так:
Threshold:1
Infectious Period:2
Display:2
s
Я просто поступаю неправильно? Или есть более простой способ сделать это? В проекте еще много работы, и я застрял на шаге 1.