Synfire's Guide To C Programming

2. Standard I/O

Standard Input and Output allows programs to inform the users, and get information from a user. There are several functions that you will learn to use before you can continue. Now in this section I will just name the function then describe how and when to use it.

This shit is kinda boring for the seasoned programmer, cause it's used so much that it's like second nature, and I don't really have the patients for a long tutorial covering how printf() sends data through your computer to your monitor... :| Honestly there are more, but these will be the only two you need to know.

I've never used the others and you probably won't either.

printf() - prints formatted text to the Standard Output.

printf.c
#include <stdio.h>

/***************************************************/
/* Never-mind this part it will become clear later. */
int VarInt = 1;
float VarFloat = 3.1902;
char VarChar = "a";
char *string[] = "This is a string!";
/**************************************************/

int main()
{
    printf("Hello World!\n");
    /* prints Hello World! on a line by itself to the screen */

    printf("int:\t%d\n", VarInt);
    /* prints 'int:      1' to the screen */

    printf("float:\t%f\n", VarFloat);
    /* prints 'float:      3.1902' to the screen */

    printf("char:\t%c\n", VarChar);
    /* prints 'char:      a' to the screen */

    printf("string:\t%s", string);
    /* prints 'This is a string!' to the screen */

    return(0);
}
You can also pass more than one variable through printf but they have to be listed in the order in which they appear, I know you have no idea what the hell I'm talking about 'variables' but you'll learn about them in the next section.

scanf() - reads formatted text from the Standard Input.

scanf gets user input, this works the same as printf except your assigning to the variable instead of reading from it. When you assign a value using scanf() you must always precede the variable with an &.

I'm not going into why, it has to do with the addressing, because that would just be a waste of time. Just make sure you do it...

scanf.c
#include <stdio.h>

int Number;
int main()
{
    printf("Enter a number between 1 and 10: ");
    scanf("%d", &Number);
    printf("Your choice was %d.", Number);
    return(0);
}
Easy enough! scanf assigns what the user types to 'Number' and then printf prints it. Understand? Good lets move onto variables.

< < < Lesson 1: Basic Structure | Lesson 3: Variable Basics > > >