-
File I/O logic error
Hi,
I'm quite a newbie around C, and I am trying to make a program that, among other things, asks the user for his name, surname and telephone number and saves it to a file.
I've managed to save the name and surname correctly, but when it comes tu the telephone, the program saves bizarre numbers instead of the one typed by the user.
The function in charge of file creation is as follows:
Code:
int save_profile(char type) {
char surname[N];
profile user; // A structure defined through typedef
FILE *puser;
fflush(stdin);
printf("Insert your surname: ");
gets(user.surname);
strcat(user.surname, ".txt");
if ((puser=fopen(user.surname,"w"))==NULL) {
printf("Error creating your profile\n");
system("PAUSE");
return 1;
} else {
printf("Insert your name: ");
gets(user.name);
fputs(user.name,puser);
fprintf(puser,"\n");
fflush(stdin);
fputs(user.surname,puser);
fprintf(puser,"\n");
fflush(stdin);
printf("Insert your phone number: ");
scanf("%c",&user.phone);
fprintf(puser,"%d",user.phone);
fflush(stdin);
fputc(type,puser);
return 0;
}
fclose(puser);
}
If the user types, for example, "John" as his name, "Walter" as his surname and "6123123123" as his phone number, the filename will be Walter.txt and it will contain:
John
Walter
651241A <---- This is the cause of my headache
(I've tried trating the phone number both as an array of ints and as a string of chars, no difference)
Should I fopen the file in "wb" mode?
Thanks
-
And, you defined "user"/profile as what?
Post the structure declaration.
The user.phone is of what type?
This line implies it is a single character.
Code:
scanf("%c",&user.phone);
This line implies it is a integer.
Code:
fprintf(puser,"%d",user.phone);
It should be an array of characters. Using "%s" as printf/scanf.
Flushing stdin in is undefined; therefore you should NOT do it.
Tim S.
-
The different treatment of user.phone is just a result of me trying to blindly fix the error. Originally, it was defined and treated as a string throughout the program.
Thanks for your help, I found and fixed the problem which was, apparently, related to the definition of a related variable in another function.
-
Never use either gets() or fflush(stdin)