C - Read user input

I have a program in which user input is required, the user enters the number 1-8 to determine how to sort some data, but if the user simply clicks, another function is entered. I get a general idea of ​​how to do this, and I thought that I would be fine, but I am having some problems when the user simply presses the enter key. Currently my code is as follows:

//User input needed for sorting.    
fputs("Enter an option (1-8 or Return): ", stdout);
fflush(stdout);
fgets(input, sizeof input, stdin);

printf("%s entered\n", input);  //DEBUGGING PURPOSES

//If no option was entered:
if(input == "\n")
{
    printf("Performing alternate function.");
}
//An option was entered.
else
{
    //Convert input string to an integer value to compare in switch statment.
    sscanf(input, "%d", &option);

    //Determine how data will be sorted based on option entered.
    switch(option)
    {
        case 1:
        printf("Option 1.\n");
        break;

        case 2:
        printf("Option 2.\n");
        break;

        case 3:
        printf("Option 3.\n");
        break;

        case 4:
        printf("Option 4.\n");
        break;

        case 5:
        printf("Option 5.\n");
        break;

        case 6:
        printf("Option 6.\n");
        break;

        case 7:
        printf("Option 7.\n");
        break;

        case 8:
        printf("Option 8.\n");
        break;

        default:
        printf("Error! Invalid option selected!\n");
        break;
    }   
}

Now I changed the if statement to try input == ", input ==" "and input ==" \ n ", but none of them work. Any advice would be greatly appreciated. Currently from what I see , the original if statement will work, and the code will jump to the else part, and then print the default case.

, , , :

char input[2];          //Used to read user input.
int option = 0;         //Convert user input to an integer (Used in switch statement).  
+5
6

, (if (input == "\n")). C "" , strcmp() ==. : if (input[0] == '\n') .... char , .

+8

Try:

#include <string.h>

if(strcmp(input, "\n") == 0)

if ( input == ... )

, C, .

+2

sscanf, , "", "Enter" , 0

: strcmp , "==".

+1

Try:

input [0] == '\n'

( * input == '\n')

+1

,

if(input == "\n")

"\n",

, literal\n,

if(input[0] == '\n')

'\n'

+1

, , .. . "\n" , ( , char *). , input char .

(*input == '\n')

Should work as you plan.

0
source

All Articles