Okay guys, I may have broken it again.
Quick recap, I am trying to read filename.xyz
Code:
4
User description
X -0.906801 0.569837 0.066005
X 0.956585 -0.258900 0.342064
X -0.962633 0.494832 0.380356
X -0.259093 0.292540 0.854958
where the user description is up to 100 characters.
I am using the following code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/*Start the programme*/
int main()
{
FILE* input;
int N=0;
double T;
int i, j;
input=fopen("filename.xyz", "r");
fscanf(input, "%d", &N);
printf("N has been read as %d\n", N);
char buf[100];
fgets(buf, 100, input);
printf("Description is %s", buf);
double array[N][3];
double **ptr;
ptr=malloc(N*sizeof(double*));
i=0;
for (i=0;i<N;i++)
{
ptr[i] = malloc(3*sizeof(double));
}
char type[N];
i=0;
for(i=0;i<N;i++)
{
fscanf(input, "%s", &type);
printf("type is %s\n", type);
j=0;
for(j=0;j<3;j++)
{
fscanf(input, "%lf", &array[i][j]);
}
}
fclose(input);
exit(EXIT_FAILURE);
}
In my output 'user' appears as type[0] and 'description' appears as type[1] before having 'X' correctly as type[2] and type[3].
I would guess that I am using fgets incorrectly?
Basically I want to do the following;
1) Read N from line 1 (ignoring leading whitespace) and store in N
2) Read entire line 2 and store as character string which I can output later. (read until newline?)
3)For next 'N' lines, store first character as type, and next 3 doubles in array[i][0], [i][1], and [i][2].
Could you please tell me what I am doing wrong with the description and whether the rest of the code is correctly allocated memory etc.
Thanks and I hope this is enough code for you Adak.
I also tried
Code:
while(fgets(buf, 80, input) != NULL)
{
puts(buf);
printf("Description is %s", buf);
}
which at least keeps user description together...but also prints the rest of the file under 'buf' (I guess because of the != NULL)?