Skip to main content Skip to navigation

2.3 Simple input/output

Printing out data

You will already have seen how we can get C to output formatted information, using printf. printf is actually a standard library function in C. The format for the printf statement must be contained within the parentheses, and comprises a sequence of regular characters (which are output in unmodified form) and conversion specifications (which control how variables/constants are printed out) that appear between double quotation marks, followed by the actual variable/constant names you wish to print out (separated by commas)

You will already have seen in the last example, that to print some text plus the value of a float variable, you had to include a line such as

printf("The value for element is %f \n", element);

In this case, %f is an example of a conversion specification. Below is a table of conversion specifications for different types:

Specifier Type
%d int
%f float or double
%e float or double in scientific notation
%c character
%s character string (char*)

Putting it into Practice:

In this example, edit your existing code so that it follows the code given below. This will give some example of printf in action;
#include <stdio.h>
int x = 5;
char str[] = "try it today!";
char c = 'z';
float pi = 3.1415926;

int main()
{ printf("\t%d %s %f %s %c\n", x, str, pi, "some text", c); return 0; }
Compile and run this code. The output should be:
       5 try it today! 3.1414593 some text z

The \t indicates a tab, just at \n indicates a newline

Note that your value of pi is rounded off by one decimal place. By modifying the conversion specification, you can change how the each particular variable is placed in output. For example:

 printf("%10.4d", x);

would yield this output:

             0005

The . allows for precision. This can be applied to floats as well as integers. The number 10 puts 0005 over 10 spaces so that the number 5 is on the tenth spacing.

A digression on string handling

This is just to introduce a few standard library function calls that come in handy when dealing with strings. The first is strcpy, which copies one string into another string. The next is strcat, which concatenates one string onto the end of another string. Finally, there is strlen, which returns the length of a string. Their usage is summarised in the code fragment below:

#include <stdio.h>
#include <string.h> char title[] = "skywalker"; char name[20]; int length;
int main()
{ /* copy string "title" into string "name" */ strcpy(name,title); printf( "title: %s\n", title); /* add the string ", luke" onto the string "name" */ strcat(name,", luke "); printf("name: %s\n",name); /* get the length of this string */ length=strlen(name); printf("this string is %d chars long\n",length); return 0; }

Reading in data

There is a counterpart to printf known as scanf that can be used for reading in data. However, most people are of the opinion that scanf is not very easy to use, and rather easy to use incorrectly. The alternative is to use two other functions known as fgets and sscanf.

fgets reads in a string as input. The general form of fgets is:

 fgets(name, sizeof(name), stdin);

name is the name of the character array. The input is read into this array.

sizeof(name) indicates the maximum number of characters to be read, plus one for the newline.

stdin indicates the source of the input - e.g. it can be from a file, or typed from the keyboard, and in this case it is from the keyboard.

Putting it into Practice:

In this example, you will write code that will read in some text from the keyboard and print it out again. Into a new .c file, type in the example code below;
#include <stdio.h>
char name[50];
int main()
{ /* prompt for input */ printf( "Input your given name: \n"); /* grab the output from the keyboard */ fgets(name,sizeof(name), stdin); /* print out what you have read in */ printf("You entered the name: %s\n",name); return 0; }
Compile and run this code.

You should notice that fgets grabs the whole string, including the newline. It's often not convenient to have that newline there. To cut off that newline character at the end of the string, we need to set the second-last element of the character array to be the terminating NULL character (set its value to '\0'). To do this in general for a string of any length, you would type, say

name[strlen(name)-1] = '\0';

In order to print out numbers, you need to use another function alongside fgets, called sscanf. sscanf converts the text read in by fgets and converts it to numbers. The usage of sscanf is similar in syntax to printf, again using conversion specification. Follow the example below:

Putting it into Practice:

In this example, you will write code that will read in some numbers from the keyboard and print them out again. Into a new .c file, type in the example code below;
#include <stdio.h> 
char line[100];
int a1, a2, a3;

int main()
{ /* prompt for input */ printf( "Input three integers: \n"); /* grab the output from the keyboard */ fgets(line,sizeof(line), stdin); /* convert this text to the numbers */ sscanf(line, "%d %d %d", &a1, &a2, &a3); /* print out what you have read in */ printf("You inputted numbers: %d %d %d \n", a1, a2, a3); return 0; }
Compile and run this code.

Some points to observe:

  • sscanf takes the name of the string as its first argument (the first s of the name sscanf stands for string)
  • the middle argument in sscanf (in quotation marks) does not require a \n
  • sscanf refers not to the integers a1, a2 and a3 themselves but to their pointers (more on pointers later) as signified by preceeding each integer name with an ampersand

Instructions on how to read in input from a file, rather than the keyboard differ only in giving the file name (as declared in your code), instead of stdout, in fgets. You have to do some extra coding for the file handling. The example code below should give you an idea about how to do this;

Putting it into Practice:

In this example, you will write code that will read in some numbers from a file and print them out again. Into a new .c file, type in the example code below;
#include <stdio.h> 
/* declare a string that will be your actual file name */
const char FILE_NAME[] = "myinput.dat";
char line[100];
int a1, a2, a3;

int main() 
{
/* declare that you want to use a file, referred to here as in_file */ FILE *in_file; /* open this file */ in_file = fopen(FILE_NAME, "r"); /* grab the output from the file myinput.dat */ fgets(line, sizeof(line), in_file); /* convert this text to the numbers */ sscanf(line, "%d %d %d ", &a1, &a2, &a3);
/* print out what you have read in */ printf("You inputted numbers: %d %d %d\n", a1, a2, a3); return 0; }
Compile this code. Create a file called myinput.dat and put three integers in it, all on the first line. Run the code to see if it works. What happens if you put a number on each line? How might you address this? Hint: look at fscanf()