i made a program but it doesnt wait to take my inputs.it wants readymade inputs. but i only want to give inputs one by one.
#include<stdio.h>
void input(char a[]){
printf("%s",a);
}
int main(){
char c[50];
int choice=1;
while(choice!=0){
printf("\nEnter the number corresponding your choice\n1.Input 2. Output 3.Arithmetic");
scanf("%d",&choice);
switch(choice){
case 1:
printf("write input statement of C:\n");
fgets(c,11,stdin);
input(c);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
printf("invalid choice enter again \n");
}
}
}
here it wants input like this "1 hello" but i want to five only 1 first then wait for it to give me instructions again to give input again.
i trid only fgets but when i tried with scanf then it did ask for input as i wanted but i dont know how to take input as a string using scanf with spaces.
to understand your issues when using a language built-in functions, you can always refer to the documentation to have a better understanding of what happens.
Here, you tried
scanf()but noticed it didn't work when there was a space in the input. Reading some documentation about this function shows thatscanf()is intended to work with formatted string and that its default behaviour is to stop scanning as soon asspaceis entered.What
fgets()does is, as shown in its documentation, scanning for all input until the special character\nis entered, so basically reading a line.Formatted string is a way to tell your computer what is the shape of the data it is going to receive. You can read more about its possibilities on the wikipedia page of
printf(), which is another function making use of those formatted strings.Now, for your issue specifically, your code might not always work because
scanf("%d", pointer)only reads the number in the input; if there is a\ncharacter after the number it will stay in the input buffer, and whenfgets()is called, the first char it will get is\n, stopping its execution.What you can do is something like the following :
after the call to
scanf(), wait for a\ncharacter to be entered, discard it and then proceed to thefgets()call, like this :I said "like the following" because the above is good for you to understand what is the idead, but as pointed out by @Jonathan Leffler, it isn't not exactly safe either, what would be a safe implementation would be
where
(c = getchar())has the valuec, so this allows to check also if the input buffer is empty.Moreover, the function
scanf()has a return value, which is currently ignored in your code. This value is the number of inputs read matching the format specifier, so in your case it is the number of int input read. Ifscanf()encounter some issue with reading, it will return a negative value. Therefore, to be sure that everything works as intended, something like this is better :getchar() documentation if you want to understand how does this works exactly.