'Printing char multi dimensional arrays not working like I want to [duplicate]
#include <stdio.h>
int main()
{
FILE *fisier;
fisier = fopen("cnp.txt", "r");
int cnpuri = 0;
char cnp[10][13];
while(1){
fscanf(fisier, "%s", cnp[cnpuri]);
cnpuri++;
if(feof(fisier))
break;
}
int i;
for(i = 0; i < cnpuri; i++){
printf("%s \n", cnp[i]);
}
fclose(fisier);
return 0;
}
This is the text I'm reading:
1234567890123
1763578126765
4156156546489
5749684631654
5498654168763
And this is what it shows in terminal:
12345678901231763578126765415615654648957496846316545498654168763
1763578126765415615654648957496846316545498654168763
415615654648957496846316545498654168763
57496846316545498654168763
5498654168763
Solution 1:[1]
The problem is that the second size of the array
char cnp[10][13];
is not large enough to store the terminating zero character of entered strings.
Declare it at least like
char cnp[10][14];
Also change the while loop the following way
while( cnpuri < 10 && fscanf(fisier, "%s", cnp[cnpuri]) == 1)
{
cnpuri++;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
