Reputation: 3
I'm trying to read data from a text file into a matrix. The text file looks like this.
Object data
Format 6
1 5241.365147 -77215.356982 248612.514352 0.000014 0.000009 0.000051
2 5242.871592 -77213.351692 248614.103512 0.000013 0.000008 0.000052
...
I've searched the previous answers on this site for similar problems, and wrote the following code.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std
int main ()
{
// Initialize variables
int i, j, i_max, j_max;
i_max = 7;
j_max = 4;
//Open the input file
ifstream infile;
infile.open ("data.txt");
//Loop through the values in the text file
double data [i_max][j_max];
for (i=0; i<i_max; i++) {
for (j=0; j<j_max; j++) {
infile >> data[i][j];
printf ("%d\n", data[i][j]); //Check the input
}
}
return 0;
}
The problem I'm having is that the printf statement which I'm using to check the input only writes the value of j_max to the terminal. Any help would be appreciated.
Upvotes: 0
Views: 310
Reputation: 47844
Fixes as follows:-
i_max = 4; //this is no. of rows
j_max = 7; // this is no. of cols
std::string dummy;
getline(infile,dummy); //Skip 1st line "Object data"
getline(infile,dummy); //Skip 2nd line "Format 6"
double data [i_max][j_max];
for (i=0; i<i_max; i++) {
for (j=0; j<j_max; j++) {
infile >> data[i][j];
// Use %f format specifier for floats
printf ("%f\n", data[i][j]);
}
}
Also, please don't mix C & C++
Upvotes: 1
Reputation: 37
Does really this take part of your input file ?
Object data
Format 6
If so, just skip those lines like this:
char s[10];
infile.getline(s, 5);
infile.getline(s, 5);
I used the char array "s" to copy that first 5 character from the entire row to it. When you call getline() the reader loads all the line, so no matter how much of that row you read, it all be skipped. And make sure you declared so you can use the getline function.
#include <string.h>
And please let me know if I helped you.
Upvotes: 0
Reputation: 1902
The problem, aside from the data file parsing and the missing semi-colon, is the printf. "d" is the format code for int, but you are passing a double. You need to use "g". Or better yet, std C++ streams.
GCC will tell you this if you turn on warnings. In general, use: "-Wall -Wextra", or in this particular case "-Wformat".
Upvotes: 0