next up previous
Next: How are data represented Up: September 25 Previous: September 25


Input/Output

If you #include <stdio.h> you have access to C's standard library of I/O functions. To print a formatted string to standard output (probably your console) you can use printf:

int i= 67;
double d= 97.8;

printf("Our lucky numbers are %d and %f\n", i, d);
The %d is a format specification (aka conversion specification), which tells C to replace it with the corresponding integer argument, formatted as a decimal (base 10) integer. Unexpected results if the corresponding argument is not an integer (try a character or a double). The %f indicates either a float or a double, and there are (many) details to printf that will allow you to control the number of decimal places, alignment, etc.

If you want to get input from your standard input (probably your keyboard), you can use scanf:

int i;
double d;

printf("Type your lucky integer, then your lucky double: ");
scanf("%d %lf", &i, &d);

printf("Your lucky numbers are %d and %f\n", i, d);
The %d again matches an integer, and %lf matches a double (that's an "l" [ell] not a "1" [one]). If you want to use all the features, you need to look up the arguments to scanf in a C manual. In an extreme case, type man 3 scanf.

You can input strings delimited by whitespace (similar to tokens):

char myString[10];

scanf("%s", myString); <---- why no ampersand?
The string to be scanned should have, at most, 9 non-whitespace characters. If you want to include whitespace characters up to a newline (inclusive) use fgets:
char inputLine[80];

printf("Type a line: ");
fgets(inputLine, 80, stdin);
printf("You typed: %s\n", inputLine);
Don't use gets(inputLine), since no checking is performed if the user of your program types 81 characters...

Here's an example of I/O with some standard C types, as well as some included information about float and int that will be useful in the next topic:

/* fool around with I/O */
#include <stdio.h>
#include <limits.h>
#include <float.h>

int main()
{
    char c;
    int i, imax= INT_MAX, exp_min = FLT_MIN_EXP,
      exp_max = FLT_MAX_EXP, mant_dig = FLT_MANT_DIG;
    float f;
    
    printf("Enter a character: ");
    scanf("%c", &c);
    printf("Enter an integer: ");
    scanf("%d", &i);
    printf("Enter a float: ");
    scanf("%f", &f);
    
    /* what happens if you mix up the arguments? */
    printf("You entered character: %d, integer: %f, and double: %c\n",
           c, i, f);

    return 0;

}


next up previous
Next: How are data represented Up: September 25 Previous: September 25
Danny Heap 2002-12-16