DEV Community

Olalekan Omotayo
Olalekan Omotayo

Posted on

Reading user input and displaying a prompt code in c language

Here's an example code in C language for reading user input and displaying a prompt:


int main() {
char input[100];

while(1) {
    printf("Enter a command: ");
    fgets(input, 100, stdin);

    printf("You entered: %s", input);

return 0;
Enter fullscreen mode Exit fullscreen mode


In this code, we first declare a character array input with a size of 100, which we will use to store the user's input. We then use a while loop to continuously prompt the user for input and display the input back to the user.

Within the loop, we use the printf function to display the prompt "Enter a command: " to the user. We then use the fgets function to read the user's input from the standard input stream stdin and store it in the input array. The fgets function takes three arguments: the array to store the input, the maximum number of characters to read, and the input stream to read from.

Finally, we use the printf function again to display the input back to the user with the message "You entered: ". The loop will continue to run indefinitely until the program is terminated.

πŸ‘‰Note that this is a basic example and does not handle input validation or errors. In practice, it's important to validate user input to avoid buffer overflow or other security vulnerabilities.

Oldest comments (0)