This question already has answers here:
Parsing input with scanf in C
                                
                                    (5个答案)
                                
                        
                        
                            Does scanf() take '\n' as input leftover from previous scanf()?
                                
                                    (1个答案)
                                
                        
                                4年前关闭。
            
                    
我正在使用fprintf将用户输入的值存储在文件中。代码未按预期工作(在提示“您要继续吗?Y或N:”后,程序自动获取一些值并继续循环。其次,它没有将用户输入的值存储到预期文件中。更新:我可以通过在%c之前在scanf中放置空间来让程序提示符使用是否继续循环,但仍然无法正确填充admin_db.txt文件。

#include<stdio.h>

typedef struct {

char str[30];
int a[10];

}UNIX;

int main()

{

UNIX admin;
char ch;
FILE *fp;

fp=fopen("admin_db.txt","w+");

while(1)

{
printf("\nEnter the name of admin :  ");
 scanf("%s",&admin.str);

 printf("\nEnter the age of admin : ");
  scanf("%d",&admin.a);

  fprintf(fp,"%s%t%d",admin.str,admin.a);

  printf("\nDo you want to continue ? Y or N :");
   scanf("%c",&ch);

   if(ch=='n' || ch=='N')
     break;

}

fclose(fp);

}


输出:

Enter the name of admin :  Akhil

Enter the age of admin : 23

Do you want to continue ? Y or N :        //Automatically taking some value                                        //                                        other than n or N and continuing loop.
Enter the name of admin :  sukhi

Enter the age of admin : 30

Do you want to continue ? Y or N :
Enter the name of admin :
Enter the age of admin : ^C


另外,文件admin_db.txt的sizeof为0字节。

最佳答案

您必须先刷新stdin,然后再进行其他输入。以下是可移植的方法:

int ch;
while (((ch = getchar()) != '\n') && (ch != EOF));

关于c - fprintf在C中的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32103102/

10-11 23:12
查看更多