C: Input, Variables, and Data Types (Page 1 of 4 )
In the last article we learned some simple techniques to print data to the screen using C. We also covered a little C history. In this tutorial, we will learn how to get input from the user and store that data in variables, and work with variables in general. There will, of course, be the usual wise-cracking. So let's get started.
Input = We Don't Care What You Have to Say
As we discussed in the last article, printing text to the user without any feedback is...well, wonderful really. But it isn't much fun. Just as there are several ways to print data, so too are there several ways to accept input. For the moment we are going to focus on our dear buddy, scanf_s().
Scanf_s() works in a manner similar to printf(), except it receives input from a keyboard. It can even read formatted text from the keyboard. Some of the higher functions of scanf_s() are a little beyond the scope of this article, as its prime purpose is to function on variables, but I will teach you enough to get started, and cover it more in a later article.
Want Some Gruyere with that Pinot Noir?
That's what they pay me the big bucks for folks, jokes like that. Let's jump right in and start learning to use this bad mama jama.
#include <stdio.h>
int main ()
{
char food[20];
char drink[20];
printf("What are you eating ");
scanf_s("%s",&food);
printf("What are you drinking ");
scanf_s("%s",&drink);
printf("I am going to eat your %s and drink your %sn", food, drink);
return(0);
}
This program creates two variables, which we will discuss later in a moment. It then prints a statement to the monitor, asking the user what they are eating and prompts them for a response. Once the user types in some text and presses enter, it stores what the user entered in a variable using the scanf_s() function. Next, it asks what the user is drinking and again prompts them to enter some info. Once the user does, it stores that data in our second variable. Finally, it prints out a sentence, using the values in our variables (with the %s placeholders).
If the user typed in sausage and milk at the respective prompts, the result of this program is:
What are you eating? sausage
What are you drinking? milk
I am going to eat your sausage and drink your milk
If we wanted to work with numbers, we would do so this way:
#include <stdio.h>
int main ()
{
int weight;
printf("How much do you weigh? ");
scanf_s("%d",&weight);
printf("nDAYUMMM! %d is HUGE!nnn");
return(0);
}
The result of this program is (if the user entered a number like 400):
How much do you weigh? 400
DAYUMMM! 400 is HUGE!
Note that if the user had answered 400lbs, 400pounds, 400 pounds, etc. it would have only accepted the numeric value.
Next: Variables >>
More BrainDump Articles
More By James Payne