Thread: C tutorial
View Single Post
 
 
Posted 2004-07-21, 12:32 PM in reply to Demosthenes's post starting "Chapter 1 Introduction Section 1.1..."
Chapter 2: Input/Output and type castes

Introduction Section 2.1

Last chapter you learned many of the components of a c program. I walked you through some basic programs and tried to describe how they worked. Obviously the examples above are pretty simple.

A major part in most programs is I/O. I/O stands for input/output. Input is any information that a user of a program passes to the computer and output is anything that the computer passes to the user.

Most programs that you have used probably allow you to give some user-input whether it be through entering data in a database or a simple click of a mouse. This chapter I will show you how to get user input through some of C's built in functions. I will also teach you a couple of output functions.

Character Input Section 2.2

In C separate functions are used to take input from a user. The code to get input for each variable type differs slightly from other variable types. This means that the function to take in an integer value would differ slightly from the function used to take in a double value which would differ from the function to take in a character. In this section I will show you two functions you can use for character input from the keyboard.

First function is getchar() and it's format looks something like this:

PHP Code:
char ch getchar(); 
That statement takes whatever is typed onto the keyboard and assigns it to ch. Unfortunately there is a drawback to this function. Once a user has input a character it waits for the user to hit enter before it executes the function. If you tried to type many characters before you hit enter in our previous example, getchar() would take the first character you typed and assign that to ch. A user of a program that uses the getchar() function could easily be confused by this unless he is properly instructed on how to use the program.

Thankfully there is a solution to this problem. Under the library conio.h there is a function called getche(). It's usage is identical to that of getchar(), the only difference is that once a character is pressed it automatically continues with the program instead of waiting for the user to hit enter.

Numeric Input Section 2.3

Many times, when you write a program, you require that the user enter a numeric value
instead of a character value. In this case there is a function called scanf(). scanf() is a powerful and flexible function. It can take input for any of the numeric data types, and in fact it can also
take character input. For now, I will only show you how to get input for an integer, double, float variable.

To get integer input, use the scanf() function like this:


PHP Code:
int num;
scanf("%d", &num); 
The first argument is a string which tells the function which type of variable the second argument will be. "%d" lets the function know that it should expect an integer input. The first argument must be in double-quotes. The second argument is the name of the variable. It must be followed by &. I will explain why in a different chapter. If you typed that segment of code above into your compiler, compiled, and ran it, it would wait for the user to enter a number, take the value and assign it to the variable num. It is always a good idea to prompt your users to let them know exactly what type of input you are looking for using printf().

If you want to get a float from the keyboard, simply change "%d" to "%f", and if you want to get a double from the keyboard, all you need to do is use "%lf" in place of "%d".

Output Section 2.4
Until now, you've been using printf(), but I haven't really told you to much about it. Well, it's finally time to go into depth about printf(). I've already covered the simplest form of printf(), which is:

PHP Code:
printf("Whatever you want to output"); 
Now it's time to expand on the capabilities of printf(). What if you wanted to tell printf() to go to the next line, or put double quotes as part of the output. The way to tell the function to do those things is by using escape sequences. Escape sequence starts with a backslash which is followed by a character or characters which tell the function how to act. Escape sequences act as characters for the most part, meaning that they can be assigned to a character variable. Here are some of the escape sequences:


\n next line
\t tab
\" double quotes
\' single quote
\\ backslash
\? question mark


You put these escape sequences into printf() like you would anything else. Let me demonstrate how to use escape sequences by a two simple programs.

PHP Code:
#include <stdio.h>
    
int main(void)
{
    
printf(" line one line two line three");
    return 
0;

Prints:


line one line two line three


Now, if we were two use the \n escape sequence to make a newline, it would look something like this:

PHP Code:
#include <stdio.h>
    
int main(void)
{
    
printf(" line one \n line two \n line three");
    return 
0;

This would print:


line one
line two
line three


Recall earlier, where I said that an escape sequence is a character, and that it can be assigned to a char variable. You do this by putting the escape sequence within single quotes.

PHP Code:
char c '\t' 
That assigns the tab escape sequence to the variable c.

I've now shown you how to output something that is hard-coded, but lets say you wanted to output the value of a value of a variable. printf() allows this to be done by using format specifiers. A format specifier begins with a % and determines how the argument it is referring to will be displayed. As far as I know, printf() can take an unlimited amount of arguments. Here is a list of the format specifiers that you will be using the most (I will add more as the tutorial progresses):


%d integer
%c character
%f float
%% percent sign


I guess those are it for now. Here is a short, trivial program which demonstrates how to use those format specifiers correctly:

PHP Code:
#include <stdio.h>

int main(void)
{
    
int i 6;
    
char c 'f';
    
float x 6.00;
    
printf("Here is the output: %d %c %f",  icx); 

    return 
0;

The output to that program would be:

Here is the output: 6 f 6.00

Notice how that printf() statement is set up. The format specifiers are within the string that is supposed to be displayed, and the variables that correspond to each format specifier are then listed after the string, separated by commas. The string is one argument, and the other variables are separate arguments. Recall from Chapter 1 that each argument in a function is separated by a comma. A call to printf() can have virtually an infinite amount of format specifiers and/or escape sequences.

Data Type Modifiers Section 2.5

You already know the 5 basic data types in C: char, int, float, double, and void. All of those data types, except void can be modified so that they better suit what you want to do with them. Each modifier does different things depending on what type of variable you associate the modifier with. The modifiers are:


long
short
signed
unsigned


Long can be associated with ints or doubles. When associated with ints, the long modifier can have varying effects which is determined by the environment you are using and the compiler that you are using. Check your compiler's documentation if you want to know the exact effects that long will have with your ints. When associated with doubles, the long modifier basically doubles its precision. I believe that short is only associated with ints, and its effects vary as well. Again, you will have to check your compiler's documentation. The signed modifier makes an integer signed, but since integers are signed by default, it's usually pointless to use signed with integers. Signed is usually used with chars. Unsigned is used with ints or chars as well. As the name implies, using this modifiers means that the values your variables hold can't be negative. Here is an example of how to declare a variable using a data type modifier:

PHP Code:
unsigned int x
A little info about char Section 2.6

One thing that you should know is that the char data type and int data type are basically interchangeable in C. This is because a character variable actually holds a number. This number, once referenced as a character by the %c specifier, is then outputted as whichever character corresponds with that number on the ASCII table. Similarly, when you input a character with scanf(), it stores a number which corresponds on the ASCII table with the character that you entered. Try the following statements in a program:

PHP Code:
char ch 'K';
printf("%d"ch); 
Look at the output. Now try this:

PHP Code:
int i 75;
printf("%c"i); 
For the first set of statements, the output should have been 75. For the second set of statements the output should be K.

Type casts Section 2.7

The C programming language allows you to temporarily transform a variable type into another variable type by using type casts. Lets say you have a floating point variable that you want displayed as an integer. This can be accomplished using type casts, although you would lose the numbers precision. It could work the opposite way as well. An integer could be type casted into a float as well. The general form of a type cast looks like this (this is not actual code):

PHP Code:
(typevalue 
Here is a short little program which assigns a value to a double variable, and then type casts it into an integer:

PHP Code:
#include <stdio.h>
    
int main(void)
{
    
double d 6.2;
    
int x = (int) d// the double variable d is casted into an integer
    
printf("%d"x);
    return 
0;

This could also be rewritten as:

PHP Code:
#include <stdio.h>

int main(void)
{
    
double d 6.2;
    
printf("%d", (int) d// the type cast is in the function itself this time
    
return 0;

Conclusion Section 2.8

If I have done a good job teaching, you should have learned basic input/output, type casts, and data type modifiers in this chapter. If you have any questions PM me, or just post them here. As an exercise, try writing a program which prompts a user to enter a character, get the character using getche(), and then write a function to convert the character to its ASCII value. I'll post all the answers to my exercises at the very end of my tutorial, but since that can take a while if you want the answer sooner, PM me. As always, I look forward to any feedback.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes