c - scanf() to get in the string on the second time -
what wrong scanf() in string on second time, can't input string on second time. not sure error occurs, can't program function well
#include <stdio.h> #include <stdlib.h> int main() { //variables decleration char staff_name1[31]; char staff_name2[31]; float sales1, sales2; //input printf("enter staff name\t> "); scanf("%[^\n]s", staff_name1); printf("enter sales amount\t> "); scanf("%f", &sales1); printf("\nenter staff name \t> ");//error,can't input string fflush(stdin); scanf("%[^\n]s", staff_name2); printf("\nenter sales amount\t> "); scanf("%f", &sales2); printf("\n"); //output printf("staff name\t\t\t\tsales amount\n"); printf("===================\t\t=============\n"); printf("%-20s \t%12.2f\n", staff_name1, sales1); printf("%-20s \t%12.2f\n", staff_name2, sales2); }
my output of code below:
warning: program uses gets(), unsafe. enter staff name > kh s enter sales amount > 134.14 enter staff name > enter sales amount > 141243.14 staff name sales amount =================== ============= kh s 134.14 141243.14
i can't input second staff name. can please me solve this??
fflush(stdin);
is undefined behaviour in standard c. flush newline character, use getchar()
instead.
printf("\nenter staff name \t> "); getchar(); scanf("%[^\n]s", staff_name2);
i use fgets()
instead of scanf read line , trim newline if necessary, offers better control on invalid inputs being entered user , against buffer overflows.
Comments
Post a Comment