Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Reading user input

Tags:

c

user-input

I have a program where user input is required, a user types in a number 1-8 to determine how to sort some data, but if the user just hits enter a different function is performed. I get the general idea of how to do this and I thought what I had would work just fine but I'm having some issues when it comes to when the user just hits the enter key. Currently my code looks 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've changed the if statement to try input == "", input == " ", and input == "\n" but none of these seems to work. Any advice would be greatly appreciated. Currently from what I can see, the initial if statement fails and the code jumps to the else portion and then prints the default case.

Just to be clear the variables I declared for this code are as follows:

char input[2];          //Used to read user input.
int option = 0;         //Convert user input to an integer (Used in switch statement).  
like image 787
oJM86o Avatar asked Feb 25 '10 00:02

oJM86o


1 Answers

The problem is in how you're doing the string comparison (if (input == "\n")). C doesn't have a "native" string type, so to compare strings, you need to use strcmp() instead of ==. Alternatively, you could just compare to the first character of the input: if (input[0] == '\n') .... Since you're then comparing char's instead of strings, the comparison doesn't require a function.

like image 156
Jerry Coffin Avatar answered Oct 04 '22 11:10

Jerry Coffin