【发布时间】:2014-11-12 05:19:09
【问题描述】:
很难找到将正在读取的文本文件的每一行分配给不同变量的方法,我在变量上方评论了显示该变量的文本文件中的一行的外观。我想知道我可以通过什么方式使用 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;
}
【问题讨论】:
-
您正试图同时解决几个问题。分解它,先解决一个更简单的问题。并且独立地开发新功能,而不是嵌入到大量其他代码中。
-
我首先要解决什么更简单的问题?
-
我会使用
std::vector<string>来保存文本文件的每一行。我首先将文件逐行读取到该向量的连续元素中并关闭文件。然后,我将阅读并将读取的行分解为您记录的物种的每个实例。每组三行将填充物种具有的 3 个属性中的每一个。您只需要对前两行进行特殊处理即可。 -
谢谢,我现在正在使用向量,完成后我会更新代码。
-
我将如何设置一个向量来获取树组的信息?我似乎找不到任何可以提取信息的资源。
标签: c++ object c++11 vector ifstream