简体   繁体   中英

scanf catches char type string with \0 and bunch of zeros after in C

I'm working on enumerations in C and can't find the source of problem in the following example that, the output is always "Sorry!":

#include <stdio.h>
#include <stdlib.h>

typedef enum
{
  summer, winter, fall, spring
} season;
void printPhrase (season s);

int main(void)
{
    printf("What's your prefered season? ");
    char seasonHold[10], seasonHold2[10];
    scanf("%s", seasonHold);
    for (int n = 0; n < strlen(seasonHold); n++)
    {
        if (n != '\0')
            seasonHold2[n] = seasonHold[n];
    }
    printPhrase (*seasonHold2);
    return 0;
}

void printPhrase (season s)
{
    if (s == summer)
        printf("It's hot out!\n");
    else if (s == fall)
        printf("It's getting cooler!\n");
    else if (s == winter)
        printf("Should be really cold!\n");
    else if (s == spring)
        printf("It should be lovely outside!\n");
    else
        printf("Sorry!\n");
}

The problem is whatever input I enter, there's always one output: Sorry! Thanks.


Also, this can solve the matter: I could manage it by changing main function into following:

int main(void)
{
        printf("What's your prefered season? ");
        char seasonHold[10];
        scanf("%s", seasonHold);
        if (seasonHold[0] == 's')
            printPhrase (summer);
        else if (seasonHold[0] == 'f')
            printPhrase(fall);
        else if (seasonHold[1] == 'p')
            printPhrase(spring);
        else if (seasonHold[0] == 'w')
            printPhrase(winter);
        return 0;
} 

Enums are like constant integers. Here: summer=0, winter=1,...

seansonhold is a char*. By dereferencing it you get a char. This char will then be converted to a 'season' type because char->int does not give compiler errors.

So you basically test here if the first byte of your char array is equal to 0,1,2..

If you are sure seasonHold is null-terminated (it will be here), you can use a pointer and while loop to accomplish what you want:

char *ptr = seasonHold;
n = 0;
while (*ptr++) {                    /* same as saying while (*ptr++ != '\0') */
    seasonHold2[n] = seasonHold[n]; /* could also do: seasonHold2[n] = *ptr; */
    n++;
}
seasonHold2[n] = 0;                 /* null-terminate */

Additionally, if you would like to dynamically allocate seasonHold2 , you can simply declare it as a pointer, include string.h and use strdup to copy seasonHold to seasonHold2 , eg:

#include <string.h>
...
char *seasonHold2;
...
seasonHold2 = strdup (seasonHold);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM