Reputation: 61
I have my txt file
4
110
220
112
335
4 is the number of lines and 4*3 the number of int. I have to read "4" then read the remaining and input them into an array
This is what I have
void main(){
int a,n;
int i=0,j=0,k[30]; //
int *N;
FILE *fp = fopen("test.txt", "r");
if(fscanf(fp, "%d", &a) != 1) { //
// something's wrong
}
n=3*a; //3*a numbers in the file
N = malloc(3 * a * sizeof(int));
for(i = 0; i <n;++i) {
int result=fscanf(fp, "%d", &N[i] );
}
fclose(fp);
for(j=0;j<3*a;j++){
k[j]=N[j];
}
printf("%d",k[0]);
}
When I print k[0]
it was supposed to print "1" but instead the whole line "110" is printed
Is there any other way to do this???
Upvotes: 3
Views: 192
Reputation: 111259
The format specifier %d
does not specify a length, so fscanf
will read as many digits as it can; this is why you get 110 instead of just 1.
If you specify a length, like %1d
, it will only read as many digits as you tell it to:
for(i = 0; i <n;++i) {
int result=fscanf(fp, "%1d", &N[i] );
}
Upvotes: 3
Reputation: 43518
The fscanf(fp, "%d", &N[i] )
will catch a number and not a digit. So
fscanf(fp, "%d", &N[0] ) //will catch 110
fscanf(fp, "%d", &N[1] ) //will catch 220
...
If you want to catch digits in your array you have to use the following code:
for(i = 0; i <n;++i) {
int result=fscanf(fp, "%c", &N[i] );
if (isdigit (N[i])) N[i]-='0';
else i--;
}
Upvotes: 2
Reputation: 929
When you use fscanf with %d format parameter, it retrieves an integer type from the file. Since 110 and the others are all integers, it will directly fetch 110 from file.
So you can either use fscanf with %d parameters in a loop which iterates for a times, or if you want to get it character by character, you can use fscanf with %c parameter but it needs much more effort. So, you should use fscanf with %d parameter and fetch all digits from it by a loop for every number.
Upvotes: 2