02 May 2012

scanf and gets

scanf

scanf is used to allow a program to get data from the keyboard.

int input;
printf("Please enter an integer");
scanf("%d%*c", &input);

These instructions will display a prompt to the operator and then stop the program until the operator keys in an integer and presses <Enter>. The integer entered will be stored in the variable named "input".

NOTES:
  • Use scanf for only one data at a time. If you require multiple inputs, use a separate scanf for each one.
  • You must insert the '&' before the variable name for all data types except strings. For strings the '&' is optional. If you break this rule your program is guaranteed to end badly.
  • The '%*c is not a requirement, but is advisable. The reasons for this will be explained later.
gets()

When used with '%s' to input a string scanf can only accept one word at a time (input  stops when a space is detected)
The Get String function (gets) will input all data from the keyboard until it detects that the Enter Key has been pressed. The format is: gets(VariableName);


No comments:

Post a Comment