简体   繁体   English

用 C 语言扫描一个单词

[英]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".嘿,我得到了这个代码,我需要扫描用户的输入(ANO/NE)并将这个输入存储到变量“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/ ).您应该知道的第一件事是 char 是一种由 1 个字节组成的数据类型,用于存储单个字符,例如 'a'、'b'、1、2 等......有 256 个可能的字符是通常由 ASCII 表 ( 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.由于 odpoved 是一个字符串,您需要将其设为 char* 或等效的 char [] 类型,它是指向字符数组(字符串)中第一个 char 的指针。 The last char in a string is always a terminator byte '\0' used to indicate the end of a string.字符串中的最后一个字符始终是终止符字节 '\0',用于指示字符串的结尾。 The null terminator is automatically inserted when the speech marks are used eg "sometext" or when %s is used to get input. null 终止符会在使用语音标记(例如“sometext”)或使用 %s 获取输入时自动插入。

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.因此,要比较字符,您需要使用包含 string.h 库时提供的 strcmp function。 There are many other useful string functions such as strlen which tell you the length of the string etc.还有许多其他有用的字符串函数,例如 strlen,它可以告诉您字符串的长度等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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