You’ve already discovered that printf( ) serves to display values in C.
For obtaining user input, scanf( ) function can be utilized.
Display a number provided by the user.
// Create an integer variable that will store the number we get from the user // Ask the user to type a number // Get and save the number the user types // Output the number the user typed |
The scanf() function requires two arguments: the format specifier for the variable (%d in the above example) and the address-of operator (&myNum), which stores the memory address of the variable. Tip: In the upcoming chapter, you’ll delve deeper into memory addresses and functions. |
The scanf() function also permits multiple inputs, as demonstrated in the following example where an integer and a character are accepted.
// Create an int and a char variable int myNum; char myChar; // Ask the user to type a number AND a character // Get and save the number AND character the user types // Print the number // Print the character |
You can also obtain a string input from the user.
Display the name provided by the user:
// Create a string char firstName[30]; // Ask the user to input some text // Get and save the text // Output the text |
Note: When using strings in scanf(), it’s essential to specify the size of the string/array (in our example, we used a sufficiently high number like 30 to ensure it can store enough characters for the first name), and there’s no need to use the reference operator (&). |
However, the scanf( ) function is limited in that it treats spaces (whitespace, tabs, etc.) as terminating characters. Consequently, it can only process a single word even if multiple words are inputted. For instance:
char fullName[30];
printf(“Type your full name: \n”); printf(“Hello %s”, fullName); // Type your full name: John Doe |
In the example provided, while one might anticipate the program to output “John Doe,” it only outputs “John.”
That’s why, when dealing with strings, the fgets() function is commonly employed to read an entire line of text. It’s important to include the following arguments: the string variable’s name, sizeof (string_name), and stdin:
char fullName[30];
printf(“Type your full name: \n”); printf(“Hello %s”, fullName); // Type your full name: John Doe |
Utilize the scanf() function for receiving a single word as input, and opt for fgets() when handling multiple words. |