In: Computer Science
New to C programming and I am stuck. The program will print "no input" if no input is given. If a command line argument is given the program will print "input:" followed by the user input. Below is the code I put together to do as desired but I get errors. What do I need to fix to get my code to compile correctly?
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char input;
scanf("%c", &input);
if (input == NULL)
{
printf("no input");
}
else
{
printf("input:",input);
}
return 0;
}
The mistakes i am able to find are :-
a) In the if condition , ( if ( input == NULL ) ) , you are trying to check if the user has not enterned any character , so if the user has not enterned the character the character input will be a null character and can be compared by the checking if input == '\0' . Here backslash zero or escaped zero ( \0 ) is assigned to a character which is null. So your if condition will become ( if( input == '\0' ) ).
b) Now in the else condition , ( else { printf("input:",input)} ) , whenever you want to print any variable using the printf function in C langauge , you need to use the format specifier for that variable in the printf statement. For example the format specifier for int is %d , for char it is %c. So the newly modified else statement will become ( else { printf("input: %c",input)} ) . I have used %c format specifier here because input is of type char.
So the modified code will become :-
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char input;
scanf("%c", &input);
if (input == '\0') //changed this line
{
printf("no input");
}
else
{
printf("input: %c",input); //changed this line
}
return 0;
}