How to read a line from the console in C?
To read from the console in C programming language, you can use the scanf() function. The scanf() function takes a format string and a pointer to a variable as its arguments. The format string specifies the format of the input, and the pointer to the variable specifies the location where the input will be stored.
Reading Integers
In this example, the program prompts the user to enter an integer, reads it using scanf, and stores it in the variable num. It then prints the entered integer.
The format string "%d" specifies that the input is an integer. The pointer to the variable number specifies that the input will be stored in the variable number.
Reading Floating-Point Numbers
Here, the program asks the user to enter a floating-point number (e.g., a price), reads it with scanf, and stores it in the price variable. It then prints the entered value with two decimal places.
Reading Characters and Strings
In this example, the program requests the user's name, reads it as a string (note: %s reads a string until it encounters whitespace), and stores it in the character array name. It then greets the user with their name.
Reading Multiple Values
This program expects the user to enter two integers separated by a space. It uses %d twice in the scanf function to read both integers and then calculates their sum.
Remember to use the correct format specifier in scanf (%d for integers, %lf for doubles, %s for strings, etc.) and provide the memory address of the variable using & (address-of operator) to store the input value correctly. Additionally, be cautious about buffer overflows when reading strings to avoid potential issues.
Conclusion
Reading from the console is accomplished using the scanf function, which allows the program to receive user input and store it in variables. Format specifiers, such as %d for integers or %lf for double-precision floating-point numbers, are used with scanf to correctly interpret and store different types of input data.