Reputation: 11
I'm working on a project that requires taking input from a file. I want to read the data such that the first column of the input file goes into the first array, 2nd column goes into 2nd array and so on.
The input file has 3 columns, of type string, int and double respectively.
So i need 3 arrays of type string, int and double. How can I read the data from the file so that each array gets it's respective data?
Thanks.
Upvotes: 0
Views: 4547
Reputation: 31435
You need to verify that you streamed correctly before pushing back into the vector, and for the sake of it, I am going to check ALL the values streamed in correctly before I push any into any of the vectors, so all the vectors will end up the same length.
std::vector< string > column1;
std::vector< int> column2;
std::vector< double > column3;
do
{
// ifs is an open stream
std::string temp1;
int temp2;
double temp3;
ifs >> temp1 >> temp2 >> temp3;
if( ifs )
{
column1.push_back( temp1 );
column2.push_back( temp2 );
column3.push_back( temp3 );
}
}
while( ifs );
This is only a "rough" example. It assumes the string is a single word. If it isn't, you need to know how to determine where that column ends, and read it appropriately.
It might be easier to create a struct for the 3 values, and to separate the reading from file to struct, and the moving from the struct to the vectors.
Obviously you will know the way the file is formatted. If you read a line into a string, then parse the string using the regex, that might be a better way to split it into the 3 component parts, in particular knowing where the "string" part ends. Perhaps your string is stored in the file within quotes.
Perhaps your columns are tab-delimited, in which case you read the string up to the tab character.
std::getline( ifs, temp1, '\t' );
If you are in control of the way your file is actually stored, this can be the simplest way to implement it.
Upvotes: 0
Reputation: 2185
Here is the code in case you need it
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
vector<int> arr1;
vector<string> arr2;
vector<double> arr3;
int main()
{
int i;
string str;
double d;
ifstream fin("myfile.txt");
if (fin.is_open())
{
while (!fin.eof())
{
fin >> i >> str >> d;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
arr1.push_back(i);
arr2.push_back(str);
arr3.push_back(d);
}
}
return 0;
}
Upvotes: 1
Reputation: 12715
Something like:
while ( i < MAX_SIZE && myFile >> stringArray[i] >> intArray[i] >> doubleArray[i] )
i++;
Upvotes: 0