Hello friends i have been facing problem in reading from a file consisting of both float values and strings.In need to read them and print them out.

The input in the text file i have been using is

0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 7.0 3.2 4.7 1.4 versicolor
4 6.4 3.2 4.5 1.5 versicolor
5 6.9 3.1 4.9 1.5 versicolor
6 6.3 3.3 6.0 2.5 virginica
7 5.8 2.7 5.1 1.9 virginica
8 7.1 3.0 5.9 2.1 virginica

The code i have written to retreive the values from the file is below.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

float test_array[6][6]={0};
int main()
{
char line [ 128 ];
float  center, temp_dist1 = 0, temp_dist2= 0;
float dmax = 43.71, tcreate = 0.1, distance_sum=0, tremove = 0.1;
static const char filename[] = "iris4.txt";
FILE *file = fopen ( filename, "r" );
char delims[] = " ";
char *result1 = NULL;

double temp_result;
int i = 1,j = 0, temp_j=0;
int result=1;

if ( file != NULL ) 
{
while ( fgets ( line, sizeof (line), file ) != NULL)
{ 
result1 = strtok( line, delims );
while( result1 != NULL ) {

temp_result = atof(result1);
test_array[i][j] = temp_result;
j++;


result1 = strtok( NULL, delims );
}
temp_j = j-1;
i++;
j=0;

}
}
printf("Values for this particular index is = %f\n %s\n ",test_array[3][4],test_array[3][5]);
getch();
return temp_j;
  
}

I am in a fix in how to retrieve both the float values and the strings in this file.I am able to retrieve fthe float values but not the strings.
Please help me out.

You always have 5 float values and then one string. Simple: parse the first 5 as strings and leave the sixth as a string. You wont be able to store the strings in the same float array though.

Use fscanf instead of fgets and strtok. E.g.:

float a, b, c, d;
    int n;
    char str[100];
    while (EOF != fscanf (file, "%d %f %f %f %f %s",
                          &n, &a, &b, &c, &d, str))
        printf ("%d %.1f %.1f %.1f %.1f %s\n", n, a, b, c, d, str);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.