Reading Columns
I am working on a C code to read in three columns of numbers from an input file and then do basic math with the numbers obtained. My input file looks like:
155.4996 38.0078 7.65
93.9968 44.9926 7.68
I am currently trying to separate co开发者_JAVA百科lumns using sscanf. To get this started I am trying to read in the columns and print just the third column to an output file. Below is what I have right now:
FILE * fp;
FILE * fp2;
char *string;
char out[2000];
char read[1000];
int column1, column2, column3;
strcpy(read, "casecent");
strcpy(out, "Diff");
fp = fopen(read, "r");
fp2 = fopen(out, "w+");
while (!feof(fp))
{
fgets(string, 1000, fp);
sscanf(string, "%d %d %d", &column1, &column2, &column3);
fprintf(fp2,"%d\n", column3);
}
I am currently getting zeros in the output file instead of numbers. I'm sure I'm just missing something small and dumb but if you could help me out it would be much appreciated.
Use float
or double
for the column variables' data types. Then use %f
or %lf
respectively in the format string for sscanf
, depending on which data type you chose.
If you want to store or print the values as integers, you'll still have to read them as floats or doubles first, then convert.
精彩评论