cstringswitch-statementc-strings

How to properly use C switch statement


I have a code snippet that I am using to learn some C

char* input( char *s ){
    scanf("%[^\n]%*c",s);
    return s;
}
void main()
{
    printf("Welcome to a string input/output example written in C! \n");
    printf("Type e to exit \n");
    printf(" \n");  
    while (0 == 0){ 
        printf("> ");
        char str[100];
        input( str );
        //All off this code works perfectly until the switch statement, which apparently cannot recognized the 'e' case:
        switch(str){
            case 'e'    :   break;
            default     :   printf("Your string is: %s \n", str);           
        }

    }
}

However, when this code is run it returns the string fine, however during the switch statement it default to the default and even if the value of "str" is "e", it returns:

Your string is: e

instead of exiting. Please help this is very strange..


Solution

  • You cant use a switch in C with a String. What you are doing now is using the pointer to the first char in the array str in the switch. Thats why always goes to the default section. A good way to do what you want would be using strcmp: int strcmp(const char *str1, const char *str2); if Return value < 0 then it indicates str1 is less than str2.

    if Return value > 0 then it indicates str2 is less than str1.

    if Return value = 0 then it indicates str1 is equal to str2.

    char str2[]="e";
    if(strcmp(str, str2))
        printf("Your string is: %s \n", str);
    else
        break;
    

    Also don't use while(0==0), use while(1) instead