I have this int count[1];
this array gives me 3 Rab
output! but it has only 2 capacity and i wondered why?!
struct MEMBERS
{
int code;
char Fname[40];
char Lname[40];
int Pnum[20];
float bedeh;
float credit;
int count[1];
struct meroDate issued;
struct meroDate duedate;
};
struct MEMBERS b;
int main()
{
int i = 0, line = 5;
char w[100];
int str[100];
FILE *myfile;
myfile = fopen("Members.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fgets(str,2,myfile);
strncpy(b.count, str, 1);
i++;
printf("%s",b.count);
}
fclose(myfile);
return 0;
}
my Members.txt
contains:
3
Rebaz salimi 3840221821 09188888888
4
95120486525
95120482642
count
is an array of integers which can hold only one element. You pass it to functions which required char *
as arguments thus, causing undefined behaviour.
printf("%s",b.count); // %s expects char * not int[]
Also here-
strncpy(b.count, str, 1);
You need to manually copy using loop or use sscanf()
depending on your data.
Edit :-
fgets(str,2,myfile);
if(sscanf(str, "%d", &b.count[0])==1){
printf("%d\n", b.count[0]);
i++;
}
read from file and store in b.count[0]
, check return of sscanf
if successful then print it's value.
Also,
fgets(str,2,myfile);
^^^ str is int[] but fgets requires argument as char *.
So str
should be of type char *
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.