In C++, I want to read one text file with columns of floats and put them in an 2d array.
First line will be the 1st column and so on.
The size of the array is unknown, it depends on the lines and columns that may vary.
I've tried with "getline", "inFile >>", but all changes I made have some problems.
For example, Is there a way to remove the unnecessary rows/lines after the values are there?
File looks like this (+/-):
Thanks
Till now I have this:
int ReadFromFile(){
ifstream inFile;
ofstream outFile;
int nLinActual = 0;
const int nCol = 9;
const int nLin = 10;
// open file for reading
inFile.open("values.txt");
// checks if file opened
if(inFile.fail()) {
cout << "error loading .txt file reading" << endl;
return 1;
}
// open file for writing
outFile.open ("outArray.txt");
// checks if file opened
if(outFile.fail()) {
cout << "error loading .txt file for writing" << endl;
return 1;
}
// Doesn't read the first line
string dummyLine, dummyLine2, dummyLine3;
getline(inFile, dummyLine);
// Declares Array
float values[nLin][nCol];
//Fill Array with -1
for(int l=0; l<nLin; l++)
for(int c=0; c<nCol; c++)
values[l][c] = -1;
// reads file to end of *file*, not line
while(!inFile.eof()) {
for (int i=0; i<nCol; i++) {
inFile >> values[i][nLinActual];
}
i=0;
++nLinActual;
}
// Check what's happening
cout << endl;
for(int l=0; l<nLin; l++){
for(int c=0; c<nCol; c++){
cout << values[l][c] << "\t";
outFile << values[l][c] << "\t";
}
cout << endl;
outFile << endl;
}
inFile.close();
outFile.close();
return 0;
}
The easiest way is to use a vector:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
int main()
{
std::fstream in("in.txt");
std::string line;
std::vector<std::vector<float>> v;
int i = 0;
while (std::getline(in, line))
{
float value;
std::stringstream ss(line);
v.push_back(std::vector<float>());
while (ss >> value)
{
v[i].push_back(value);
}
++i;
}
}
Update: You said you needed it to be done using raw C arrays. Sure, this can be done:
int main()
{
std::ifstream in("in.txt");
std::string line;
float v[9][10];
int i = 0, k = 0;
while (std::getline(in, line))
{
float value;
int k = 0;
std::stringstream ss(line);
while (ss >> value)
{
v[i][k] = value;
++k;
}
++i;
}
}
I think this might help you. Use a vector of a vector of type float
as you are not aware of the count of number of items. This code assumes that you have a float
numbers separated by space at each line.
fstream fs;
fs.open("abc.txt",ios::in);
vector<vector<float>> floatVec;
string strFloat;
float fNum;
int counter = 0;
while(getline(fs,strFloat))
{
std::stringstream linestream(strFloat);
floatVec.push_back(std::vector<float>());
while(linestream>>fNum)
floatVec[counter].push_back(fNum);
++counter;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With