C - User Input

You can use the scanf() function to take user input from the keyboard. Here's how you can take multiple inputs, including string input, using scanf():

#include  <stdio.h>
int main() {
    int number;
    char character;

    printf("Enter a number: ");
    scanf("%d", &number);

    printf("Enter a character: ");
    scanf(" %c", &character); // Note the space before %c to consume the newline character

    printf("You entered: %d and %c\n", number, character);

    return 0;
}

In this example, the user is prompted to enter a number and a character. The %d format specifier is used to read an integer, and the %c format specifier is used to read a character. The ampersand (&) is used to pass the address of the variables to scanf().

Note that there is a space before %c in the scanf() statement to consume the newline character left in the input buffer from the previous input operation. This ensures that scanf() reads the character correctly.

Taking Multiple Inputs:

To take multiple inputs, you can use multiple calls to scanf() with appropriate format specifiers.

int num1, num2;
char name[20];
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

printf("Enter your name: ");
scanf("%s", name);

printf("Numbers: %d, %d\n", num1, num2);
printf("Name: %s\n", name);

In this example, the user is prompted to enter two numbers, which are stored in num1 and num2 using the format specifier %d. Then, the user is prompted to enter their name, which is stored in the name character array using the format specifier %s. Finally, the numbers and name are printed.

Taking String Input:

To take a string input that may contain spaces, you can use the fgets() function.

char sentence[100];

printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);

printf("Sentence: %s", sentence);

In this example, the user is prompted to enter a sentence. The fgets() function reads the input line, including spaces, and stores it in the sentence character array. The sizeof(sentence) specifies the maximum number of characters to read. Finally, the entered sentence is printed.

It's important to note that when using scanf() to read string inputs, it stops reading at the first whitespace character encountered. To read a complete line of text, including spaces, fgets() is a preferred option.

Make sure to include the appropriate header file, , at the beginning of your program to use the input/output functions.