Reputation: 1065
I have a .txt file like this, with hundreds of rows:
109787.3634 108234.1301 106952.8345 1.0000
110010.6294 108250.4733 106975.6766 1.0000
110243.5609 108312.5631 106999.9469 1.0000
110482.4885 108382.7281 107025.0583 1.0000
110724.3577 108461.8582 107051.2432 1.0000
I want the data in the first 3 columns
The values are separated by tabs after being copied from excel (I also tried saving the excel data as CSV, but had the same problem as described below).
This is my code to import the data, borrowed from various sources:
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
double data[360][3];
ifstream file("tsv.txt");
for(int row = 0; row < 360; ++row)
{
string line;
getline(file, line);
if ( !file.good() )
break;
stringstream iss(line);
for (int col = 0; col < 3; ++col)
{
string val;
getline(iss, val, '\t');
if ( !iss.good() )
break;
stringstream convertor(val);
convertor >> data[row][col];
}
}
for (int i = 0; i<360 ; ++i)
{
for (int j = 0; j<3 ; ++j)
{
cout << data[i][j] << " ";
}
cout << endl;
}
system("PAUSE");
return 0;
}
The code extracts the data and stores it in the array. However, all of the decimal places are lost, and cout returns this (note there is no rounding):
109787 108234 106952
110010 108250 106975
110243 108312 106999
110482 108382 107025
110724 108461 107051
All of this data was copied to a text file directly from excel, and the cells are formatted as "number", with 4 decimal places. I tried the same example with a CSV file and the same occurs. If I manually type the values into a text or CSV file, it will retain the decimal, but when I copy and paste the decimal places are lost. However, I need to copy and paste as I have thousands of data points in total.
Why am I losing part of my data when it is imported to C++?
Upvotes: 0
Views: 1042
Reputation: 4641
You need to set the precision when print out double numbers on standard out. I also change the code so it is a bit more generic.
#include <fstream>
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
struct numbers
{
double a, b, c;
};
int main()
{
vector<numbers> data;
ifstream file("tsv.txt");
if (!file.good())
return -1;
double a, b, c, d;
while (file >> a >> b >> c >> d) {
data.push_back(numbers{ a,b,c });
}
for (auto num : data)
{
cout << setprecision(16) << num.a << " " << num.b << " " << num.c << "\n";
}
system("PAUSE");
return 0;
}
The output is:
109787.3634 108234.1301 106952.8345
110010.6294 108250.4733 106975.6766
110243.5609 108312.5631 106999.9469
110482.4885 108382.7281 107025.0583
110724.3577 108461.8582 107051.2432
Press any key to continue . . .
Upvotes: 2