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.
Contributed by James Payne Rating: / 32 February 04, 2008
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.
Variables are objects used to store data. The easiest way to think of a variable is like a box that holds a book. You can store a book in the box, take the book out and read it, modify the book and put it back, replace the book with an entirely new book, or take it out and leave the box empty for later use. The data in a variable is just that, variable. We worked with variables in the above example to store data from the scanf_s() function.
All variables in C must be assigned a data type (you must tell the program what type of data the variable will hold). Before we can use a variable, we must declare it. We do so like this:
int my_number;
This basically tells the system, "hey, I am going to need space for a variable named my_number."
You can also declare more than one variable on a line:
int my_number, yournumber, yomamasnumber;
And lastly, we can assign a value to a variable at the same time we declare it:
int my_number =22;
This stores the value 22 in the variable named my_number.
If we wanted to store a variable in another variable, we could do that also:
my_number = yournumber;
And if you want to get weird, you can assign multiple variables the same value like so:
my_number = yournumber = yomamanumber = 1900;
Naming Conventions
Variable names can consist of letters (both upper and lowercase), numbers, and the underscore(_). They cannot begin with a number. Here are some sample names for your perusal:
There are four basic data types in C. They are Int, Char, Float, and Double.
Data Type: Int
This data type is used to store integers (whole numbers). They are usually 32 bits, though at this point I wouldn't concern myself with that. Variables of this type can hold values ranging from -2147483648 to 2147483647. Here is an example of how you would declare an int variable and store data in it:
int weight = 320;
Data Type: Char
This data type stores a single letter, number, or special character. You can also use the ASCII character set, but again, we won't be discussing that here; just know for now that the option is available. Here is a sample of a program using a char variable:
#include <stdio.h>
int main ()
{
char lyric1;
char lyric2;
char lyric3;
lyric1 = 'A';
lyric2 = 'B';
lyric3 = 'C';
printf("It's easy as %c%c%c ", lyric1,lyric2,lyric3);
return(0);
}
Data Type: Float
This data type is used for floating point values. To work, float literals must have a suffix of either f or F, as in: 3.26852f or 2.0F. Note that the float only stores single-precision floating point numbers.
Data Type: Double
This data type is very similar to the float, except that it allows you to store double-precision floating point numbers. It takes up 8 bytes typically and does not require the f or F as a suffix: 9.1298273646552717, 2.0, 3.098e+23 are all valid. If you use a number without a decimal, it will be interpreted as an int instead.
In addition to Data Types, there are also data type modifiers, which are used to...you guessed it genius, modify data types.
The Short and Long of It
Short and Long are used to modify the amount of memory a data type uses. It can either be less (short) or more (long). You use data modifiers by preceding the data type with the short or long keyword with the exception of an int, which does not need to follow the keywords. A short typically takes up 2 bytes of memory (less than an integer) and is often used for values ranging from -32768 to 32767.
Longs on the other hand are either the same size as an integer (4 bytes) or larger (8 bytes). Note that you can also use the unsigned specifier in addition to your data modifier to ensure that the values are positive and never negative. Again, you do not need to write int after this specifier. Here are some examples:
unsigned short myage;
short myage;
long yourage;
short int myage;
There are other data modifiers and specifiers, but these will do for now.
Scope
While this won't really make sense until future articles, it is important to note that variables have a lifetime (just like your goldfish you flushed down the toilet last night). There are two types of lifetimes for variables:
Local Variables
Local variables are declared at the beginning of the block they are going to be used in and can only be used in that block of code. They essentially die after that block, becoming useless to the rest of the program.
Global Variables
Global Variables are declared outside of any block and can be used from anywhere in your program, essentially never dying. Some people consider them bad programming practice, as (for example) they are harder to track down should a bug occur, but they definitely serve their purpose.
Well that is it for this article. We will cover more of the data types and modifiers as time progresses. In the next article however, we will discuss Operators and Assignments, so stick around. Or well...come back often, as you may have to wait a few days and I don't want you just sitting there, messing up my web page.