Programs are a lot more useful if users can interact with them. It is equally useful to be able to perform specific operations depending upon what input is gained from said users. That's the topic for this entry.
There are several methods that can be used to get input. We will only focus on one for now, and that is getchar. This method only gets a single character's worth of input from a user, and it does not validate the input. We will get to more advanced input and input validation in a later article. For now, this method will do well enough to explain the concepts.
#include <stdio.h>
int main( void ) {
char c;
printf("Please input any character: ");
c = getchar();
printf("\n%c\n", c);
}
The first thing that stands out in this program in comparison to others we have done is that there is a new variable type used. "char" declares a character variable. This type of variable can only handle a single character. You'll notice that in the printf statement we are now using %c for char rather than %d for decimal value. The next thing is the "c = getchar()". Two important things are happening here. First, the getchar method is getting input from the user, and secondly it is returning whatever value it is given to the character variable c.
Let's expand.
#include <stdio.h>
int main( void ) {
char c;
int i = 0;
printf("Please enter a character (n will exit): ");
c = getchar();
while (c != 'n') {
printf("%c\n", c); c = getchar();
}
return 0;
}
Here we are using a loop to control the exit of our program. The "!=" (bang equals) means does not equal. So, "while the value of variable c does not equal n" was the condition for the loop. We could structure this slightly differently with a do-while loop, but a for loop wouldn't be suitable.
#include <stdio.h>
int main( void ) {
char c;
printf("Do you like programming so far? (y/n)");
c = getchar();
if ( c == 'y' ) {
printf("Great! Move on to part v!\n");
}
else {
printf("You may want to consider something like knitting.\n");
}
return 0;
}
Here we declared our character variable c, we asked a question, we got an answer, and then we tested the answer. If the user type "y" we print one message in response, and for any other answer we print a different response.