简体   繁体   中英

Scanf for a word in C language

Hey I got this code where I need to scanf the input of the user (ANO/NE) and store this input into variable "odpoved". How to do that? What I have now looks like it is scanning just the first letter of the input.

char odpoved;

printf("Je vše v pořádku? (ANO/NE)");
scanf("%s", &odpoved);

if(odpoved == "ANO" || odpoved == "ano"){
    printf("Super, díky mockrát");
}
else if(odpoved == "NE" || odpoved == "ne"){
    printf("To mě mrzí, ale ani já nejsem dokonalý");
}
else{
    printf("Promiň, ale zmátl jsi mě. Takovou odpověď neznám!!!");
    return 0;
}

The first thing you should know about is that char is a data type consisting of 1 byte and is used to store a single character such as 'a', 'b', 1, 2 etc... there are 256 possible characters which are often represented by the ASCII table ( https://www.ascii-code.com/ ).

As odpoved is a string you need to make it type char* or equivalently char [] which is a pointer to the first char in the array (string) of characters. The last char in a string is always a terminator byte '\0' used to indicate the end of a string. The null terminator is automatically inserted when the speech marks are used eg "sometext" or when %s is used to get input.

The other mistake you have made is to compare strings with == or.= signs. This will not work as the first characters will be compared with each other. Hence to compare the characters you will need to use strcmp function provided when the string.h library is included. There are many other useful string functions such as strlen which tell you the length of the string etc.

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