Reputation: 153
I am learning file handling in C.I have this code but it is not accepting string as an input to write it to a file.Any help will be appreciated.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(void)
{
FILE * fp1;
fp1 = fopen("abc.txt","a+");
if(fp1==NULL)
{printf("An error occurred");
}
printf("Delete file?\n");
int a,c;
char name [20];
int flag=1;
int ch=1;
while(flag!=0)
{
printf("Enter id input \n");
scanf("%d",&a);
fprintf(fp1,"\n%d\t",a);
printf("Enter Name");
gets(name);
fputs(name, fp1);
printf("Enter No \n");
scanf("%d",&c);
fprintf(fp1,"\t%d\t",c);
printf("Write more then press 0 else 1");
scanf("%d",&ch);
if(ch==1)
{
flag=0;
}
}
fclose(fp1);
}
On running this code the code does not take an input after Enter Name and directly skips to Enter No.I want the output to be in a tabular form.
Upvotes: 1
Views: 126
Reputation: 111
gets()
is deprecated, don't use it. you can still use scanf()
...
as for the tabulation...think it through.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp1;
fp1 = fopen("abc.txt", "a+");
if (fp1 == NULL) {
printf("An error occurred");
}
int a, c;
char name [20];
int flag = 1;
int ch = 1;
while (flag != 0) {
printf("Enter id input:\n");
scanf("%d", &a);
fprintf(fp1, "%d\t", a);
printf("Enter Name:\n");
scanf("%s", name);
fprintf(fp1, "%s\t", name);
printf("Enter No:\n");
scanf("%d", &c);
fprintf(fp1, "%d\n", c);
printf("Again (0) or Exit(1) ?:\n");
scanf("%d", &ch);
if (ch == 1) {
flag = 0;
}
}
fclose(fp1);
return 0;
}
Upvotes: 0
Reputation: 20244
When you enter a number for scanf("%d",&a);
, you type in a number and press the Enter key. The scanf
consumes the number and leaves the newline character ('\n'
) in the standard input stream (stdin
). When the execution of the program reaches gets(name);
, gets
sees the newline character and consumes it, storing it in name
.
Firstly, never use gets
as it is dangerous as it doesn't prevent buffer overflows. Use fgets
instead:
fgets(name, sizeof(name), stdin);
Secondly, you have to get rid of the newline character. You can do this by flushing the stdin
. Or you can simply scan and discard the newline character just after reading the number from scanf
by changing
scanf("%d",&a);
to
scanf("%d%*c",&a);
%*c
scans and discards a character.
Upvotes: 1
Reputation: 2757
Use a getchar() after entering id because the \n of 1st scanf stays in buffer.
printf("Enter id input \n");
scanf("%d",&a);
getchar();
Upvotes: 2