Reputation: 197
I am making a program in C that reads a line from file and displays this line on screen My homework requires that the file must get a number from the file and make some operations on it.
I get the file content and put it in an array:
while ( fgets ( line, sizeof line, file ) != NULL )
{
strcpy(arra[i], line);
printf("array ----> %d \n", arra[i]);
i++;
}
how can I parse this content to int ?
Upvotes: 1
Views: 241
Reputation: 40145
#include <stdio.h>
#include <stdlib.h>
#define MAX_DATA_SIZE 10
int main(){
FILE *file;
char line[128];
int array[MAX_DATA_SIZE];
int i,count,sum;
file = fopen("data.txt","r");
/* data.txt:
100
201
5
-6
0
*/
for(i=0; NULL!=fgets(line, sizeof(line), file); ++i){
if(i == MAX_DATA_SIZE){
fprintf(stderr,"exceeded the size of the array.\n");
exit(EXIT_FAILURE);
}
array[i]=atoi(line);
}
fclose(file);
/*some operations */
count = i;
sum = 0;
for(i=0;i<count;++i)
sum += array[i];
printf("%d\n",sum);
return 0;
}
Upvotes: 1
Reputation: 5100
you can use atoi()
int x = atoi("string");
From your code sample
while ( fgets ( line, sizeof line, file ) != NULL )
{
strcpy(arra[i], line);
printf("array ----> %d \n", atoi(arra[i]));
i++;
}
Upvotes: 3
Reputation: 258628
If line
is a char*
, you can use atoi
to convert it to an integer.
printf("array ----> %d \n", atoi(line));
Upvotes: 3