Basic Input / Output

Basic Input/output.

Well, we already explained how you get text directly into the project via the console (or DOS box) using the Argc and Argv C commands. Now how do you get keyboard input into the project? What do you do when you need someone to type something?
There are a couple of ways to get stuff into the program, and we’ll deal with both of them here. Then we’ll explain the printf statement. That’s a fun oneJ

So lets get into it. There are two types of getting data in. There’s trapping each individual key press, and processing that, and there’s asking for a data string to be typed in, and not dealing with it until the use presses the enter key. Both ways have their advantages and drawbacks. Catching each key works well, but it’s a lot of processing, and you have to then parse the string that you get to see if it’s all legal. For instance, if you wanted a numerical string, but the user hit alphabetic keys, then you have to watch for that and prompt them if they do it wrong. Plus you have to print up on the screen the keys they are typing, so they can see them. The system won’t do it for you. The second way the system will do it for you, but it automatically prints up your input on the screen, and this can mess up nice text displays you may have created, since it will allow back spaces to move text around.


This is the command you need for the first way to get key strokes into the system. When you call this command (it’s actually located in the file library stdio.h – this means you must include the file stdio.h at the top of the C file where you call this function) the system will go away and wait for a key to be pressed. Once it has been, it will return to the program and return which key was pressed. So you’d used it like ;-

#include <stdio.h>
char getInput(void)
            char      key;
            key = getchar();
            return (key);

-         note in the use of the #include function, where we are pulling in the .h file stdio.h we use brackets rather than quotes around the .h file name. This indicates to the compiler that you want it to get it’s own pre-defined version of stdio.h. If you want the compiler to go get a .h file that you’ve created, you would use quotes around the file name instead. The difference is that with quotes you must specify to the compiler the path of the file you want to include. With <> signs, it uses it’s own built in pathing to it’s own library functions.

Ok – you can see from this example that we are just getting one key press, and returning what it is inside of the char variable key. Pretty simple. There is a lot more to this than meets the eye though. But right now, we won’t get into all the things you may need to watch out for, because it’s a huge subject, and there are some things you really need to experiment with and discover yourself. Besides, it’s late when I’m writing this :) .

scanf() and printf()

This is the second method of getting input. The scanf() command will scan the keyboard and request a specific type of data to be put in. There is actually more than one way of doing this but we’ll stick with this one for the time being.
We are going to cover both scanf and printf at the same time since they use similar syntax. You’ve seen examples of where we have lines like

Printf(“Hello %s, it’s nice to see you. You’ve been online %d times in the last day.\n”, name, logon_count);

What does it all mean? Well, the command, as you’ve probably gathered, puts up text on the screen. The stuff between the quotes is what we want to see on screen text wise. The stuff with the % signs infront of it tells the C runtime system that we want to insert some variables into the text string here, and tells it what kind of data variables we want to use. For instance %s means “there is a string that is going to go here”. %d is an integer variable. %f would be a floating point type variable. Here’s a quick list of some of the more common ones.

%d  or %i– integer goes here – this is the same for bytes, shorts and ints.
%u – unsigned decimal number
%f – float goes here
%s – this is a text string.
%x – this one displays an unsigned hexadecimal number rather than a decimal one.
%% – put in a percent sigh rather than anything else

Limiting Width.

Now there is some cooler stuff you can do here with these display modifiers. You can limit the size of the stuff you print out. Lets say you have a floating point value, but you only want to display 3 points of decimal place. How do you do that? Well, there is a helpful little modifier you can put into the % structure that allows you to specify the width of the display. Here’s an example

printf(“Well, we got a difference of %.2f between the two.\n”, diff);

In between the % and f (which signifies that we want to display a float) there is a ‘.2’. This delimits the decimal place display to two places. Note also though, that when we do this limiting of width, the display will actually round up or down the values we have. So if the value of diff was 314567.2453456 we’d actually see 314567.25 displayed.
This is a clever and powerful little modifier – we can use it for strings too. If we were to put

printf(“The part of the string we are interested in is %.*s/n”, max, string_stuff);

we can limit how much of the string sting_stuff is printed out – the exact limit being held in the variable max. There is more you can do with this, but really it’s not that useful, so we’ll just ignore it for now. If you are really interested, there are other works to look at for more details. I just want to give you the basics right now.

Inserting variables.

You’ll notice that after the string is defined, we then list – in the correct order – the variables we want to be placed in this string. So if in the original example, the variable name has “Jake” in it, and logon_count = 20, then we’d see the string

Hello Jake, it’s nice to see you. You’ve been online 20 times in the last day.

Displayed on the screen. Now, you’ll also have noticed that at the end of the string there is a ‘\n’ set of characters. What do these mean? These are what are called Escape Characters. They are a way of indicating to the printf function that we want to do something inside this string that is not just text. Like, for instance, a new line. In fact, that’s exactly what a ‘\n’ signifies. Place a new line here. There are other escape characters we can use, and here’s a list of some of them.

\n – new line
\r – carriage return
\t  – insert a horizontal tab
\b – back space
\? – insert a question mark here
\’ – insert a single quote here
\” – insert a double quote here
\\ – insert a backslash here

You get the idea.

How scanf works.

Now that we know how to format strings to get the out into the world, we can apply this to the way we get string information into the project. The scanf() command works in almost the same way as the printf() command does, with two notable exceptions. The first is that instead of just displaying text, it allows input. The second is that you don’t feed it normal variable names. Instead, you give it pointers to variables. Uh oh. Pointers. There’s that word. This is a scary subject, but I’ll give you a real quick definition. If you get it, great. If not, never mind. We will cover this one in much more depth after the practical work. Don’t worry yourself too much about this right now.

Pointers are a way of pointing at where variables sit in memory rather than the value of the variable. If we have a variable named x, and it has a value of 10, then x would equal 10. x = 10. Ok. However, this variable is actually stored somewhere in memory. We might want to know the address of this location in memory (for reasons that will become more clear later) and we can do this by looking at a pointer to x. If we put an & in front of the variable x, then we are talking about the location of variable x, not the actual value of variable x. For instance

x = 10;

Will set x to 10. Ok. However

pointer_to_x = &x;

Will give us the location in memory of the variable x inside of the variable pointer_to_x. This can be desirable, if not just because some functions demand pointers. We’ll get into implications of this later.

Now, while printf() does NOT return anything to you, scanf() DOES. If the user has typed in the type of variables information that has been requested, then the scanf will return the number of variables that have been successfully entered. Ok, lets explain that in a bit more depth. Lets say we have the lines

int ret, cell_count, cell_value;
ret = scanf(“%d %d”, &cell_count, &cell_value);

Then we are actually asking for two sets of values to be input. Lets say we input the first one correctly, for instance the value 5. Then we input the string “blah”. Obviously the string blah is not an integer value, which is what we asked for. In this case, ret will equal 1, since only the first value was input correctly.
If we entered “blah” first, then entered the value 5, we would get a ret value of 0, since the return value is the point at which the scanf function found an illegal variable type. Which obviously would, in this case, be the first value.
Assuming of course, that we entered both values correctly, we would get a ret value of 2.

Ok, we’ve covered a lot in the last few lessons, and quite frankly it’s getting boring. So next up we are going to do a little practical work. This should be more fun, and let you flex your C muscles a bit.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>