с трудным временем нахождения способа назначения каждой строки текстового файла, считываемого для другой переменной, я прокомментировал выше переменные, отображающие, как строка из текстового файла отображается эта переменная будет выглядеть. Я хочу знать, как я могу использовать forloop, чтобы иметь возможность перебирать весь текстовый файл и хранить данные для каждой из переменных, которые я прокомментировал выше, в зависимости от типа данных, которые он должен хранить. Три набора переменных все должны храниться по видам и таким образом, чтобы их можно было манипулировать. Как я могу разбить вектор на набор из трех переменных?Итерация через текстовый файл и назначение переменных для каждой строки
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string getInputFileName()
//retrieves the inputfile
{
string fileName;
ifstream inputfile;
//prompting user for filename to be opened
cout << "Enter the file name to be opened: ";
cin >> fileName;
//opening the file for input
inputfile.open(fileName, ios::in);
//checks to see if writing the input file failed
if (inputfile.fail())
{
cout << "Opening file..." << fileName;
cout << "\n";
cout << "The " << fileName << "could not be opened! \n";
cout << "1. Check if file exists. \n";
cout << "2. Check file path. \n;";
}
else
{
cout << "File: " << fileName << " was successfully opened!" << endl;
return fileName;
}
}
string getOutputFileName()
//retrieves the inputfile
{
string fileName;
ofstream outputfile;
//prompting user for filename to be opened
cout << "Enter the file name to be opened: ";
cin >> fileName;
//opening the file for input
outputfile.open(fileName, ios::in);
//checks to see if writing the input file failed
if (outputfile.fail())
{
cout << "Opening file..." << fileName;
cout << "\n";
cout << "The " << fileName << "could not be opened! \n";
cout << "1. Check if file exists. \n";
cout << "2. Check file path. \n;";
}
else
{
cout << "File: " << fileName << " was successfully opened!" << endl;
return fileName;
}
}
int main()
{
//opens clasfication file
ifstream inputFile(getInputFileName());
//declaring year and numberOfSpecies
int year, numberOfSpecies;
string line;
if (inputFile.is_open())
{
//year of file
inputFile >> year;
//echo for year
cout << year << endl;
//number of species of file
inputFile >> numberOfSpecies;
//echo for number of species
cout << numberOfSpecies << endl;
string line;
//variables i need to assign line by line and be able to manipulate
//region of species would look like this in text file: 84
//nameOfspecies would like like this in the text file: Spotted Gecko
//regionSightings would look like this in the text file: 84 95 30 25
vector<string> linesOfData;
for (int i = 0; (!inputFile.eof()) || (i <= numberOfSpecies) ; i++)
{
getline(inputFile, line, '\n');
linesOfData.push_back(line);
//echo vector!
cout << linesOfData[i] << "\n";
}
ofstream outputFile(getOutputFileName());
}
return 0;
}
Вы пытаетесь решить сразу несколько проблем. Разбейте его, сначала решите более простую проблему. И разработайте новую функциональность * в изоляции *, не встроенную в большой объем другого кода. – Beta
Какая простая проблема была бы первой проблемой, которую я решаю? – user3236101
Я бы использовал 'std :: vector' для хранения каждой строки текстового файла. Сначала я читал файл по строкам в последовательные элементы этого вектора и закрывал файл. Затем я прохожу и разбиваю прочитанные строки в каждом экземпляре вида, который вы записали. Каждая группа из трех строк будет заполнять каждый из 3-х атрибутов, которые имеет вид. Вам просто нужна специальная обработка для первых двух строк, как вы уже сделали. –
enhzflep