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

#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); printf("You entered: %d\n", num); return 0; }

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

#include <stdio.h> int main() { double price; printf("Enter the price: "); scanf("%lf", &price); printf("Price entered: %.2lf\n", price); return 0; }

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

#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s!\n", name); return 0; }

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

#include <stdio.h> int main() { int num1, num2; printf("Enter two integers separated by a space: "); scanf("%d %d", &num1, &num2); printf("Sum: %d\n", num1 + num2); return 0; }

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.