Category Archives: Input

Reading a number

In C 'A' is an int constant used to represent the character ‘A’. The same is true for digits, of course.

If you have a variable c which contains a digit (say ‘9’) you can find the numerical value by c - '0' which in this case evaluates to 9.

If you wish to read a number (such as 124) from input using getchar(), you can do as follows. First check that the current input char you have read is a digit. Do that with the function isdigit. It returns a nonzero value if you give it a digit, such as '0' or '9'. To read a number then, you can have a variable x initially set to zero, and do:

x = x * 10 + c - '0';

Do this for each input char c you read that is a digit. If we read the digits '1', '2', and '4' in sequence, x will first be 0, then 1, then 12, and finally 124!

Note that the type of c should be int, as explained here.

Input and getchar

The most basic function to read input in C is int getchar(void). Obviously, it reads one char. What might not be obvious (at least not initially) is that we should not save the returned value in a variable of type char. Instead, do as follows:

int c;
c = getchar();

Suppose you wish to read all input and use getchar() in a loop. When all input has been read, the return value from getchar() is the special value EOF which is an integer value that is guaranteed to be different from the character set used (such as ASCII). EOF stands for enf of file and its value can be -1 for instance.

Writing:

while ((c = getchar()) != EOF) {

}

Will end up in an infinite loop if the variable c has an unsigned integer type, such as unsigned char. In C we have three distinct char types:

  • signed char,
  • unsigned char, and
  • char
  • .

The last of these is either signed or unsigned and which it is is implementation defined (decided by the compiler). If it is unsigned, then c will never be equal to EOF and the loop will not terminate.

Therefore, it is best to declare c as above with type int. For the assignments in the book with downloadable files, we explicitly tell the compiler that we want char to be unsigned in order to test your code for this trap.