Back to 212 Main Page

Mobius strip

Reading in a number from the user

Though you were introduced to pointers this week, you have not dealt yet with arrays or strings in C. This makes user input a bit more challenging. Here's a bit of help:

#include <stdio.h>

void main()
  char c[10];
  int num = 0;
  printf("Enter a number: ");
  fgets(c, 10, stdin);
  num = atoi(c);
  printf("%.2f\n", num/1.0);

You can find descriptions of the printf, fgets, and atoi functions in Appendix B of the K&R book. (A description of the C Standary Library can also be found among my links for C.

Basically, this little program gets a number from the user and prints it back to the screen as a float (with no error checking). To do this, it creates a character array c that can hold up to 10 characters. After prompting the user, it reads characters into this array (which has a size of 10--hence the second parameter to fgets) from the standard input stream (stdin). The function atoi turns a string into an integer, much as Java's Integer.parseInt(String) method does. The last line is an example of using printf's formatting capabilities (%.2f means print a float with only 2 digits after the decimal place) and a quick trick to turn an int into a float (divide the int by a float).

~ztomasze Index : TA Details : ICS212 : Input Help
Last Edited: 24 Aug 2005
©2005 by Z. Tomaszewski.