C语言 如何使用 scanf 和 if 与字符串?(非常基本)



我刚刚在大学上了第一堂C编程课,我做了这个:

#include <stdio.h>
int main()
{
char answer='x';
printf("Should the crocodile eat the man? y/n ");
scanf("%s",&answer);
printf("%s",& answer);
if(answer == 'y')
{printf("the man is dead");}
if(answer == 'n')
{printf("the man still alive ");}
}

如何对字符串而不是单个字符执行相同的操作?

我尝试了很多方法,但没有任何效果。

在 C 中,字符串是字符值序列,后跟零值终止符。 字符串"hello"由序列{'h', 'e', 'l', 'l', 'o', 0}表示。

字符串存储char数组 - 数组必须足够大以容纳整个字符串加上0 终止符,因此要存储字符串"hello",您需要一个长度至少为 6 个元素的char数组。

请务必记住,char数组不必包含字符串 - 您可以使用它来存储不应解释为字符串的字符数据。 您还可以将多个字符串存储到数组中,如下所示:

/**
* Array size is determined by number of elements in the initializer
*/
char strs[] = {'T','h','i','s',0,'i','s',0,'a',0','t','e','s','t',0}; 

在此之后,strs将包含 4 个字符串:"This""is""a""test"

因此,要将字符串存储"y""n",您需要一个至少2 个元素宽的char数组。

char answer[2];

要使用scanf读取字符串,请使用%s转换说明符:

scanf( "%s", answer );

%s告诉scanf跳过任何前导空格,然后读取一系列非空格字符并将它们存储到answer数组中。 0 终止符将自动附加到数组中,使其成为字符串。

在这种情况下,你不需要在answer上使用&运算符;在大多数情况下,类型为"T数组"的表达式将被转换("decay")为类型为"指向T的指针"的表达式,因此表达式answer从类型char [2]"衰减"到类型char *

为了安全起见,您应该指定最大字段宽度,以便读取的字符数不会超过目标数组的大小:

scanf( "%1s", answer );

由于我们必须为 0 终止符保留一个元素,因此字段宽度说明符应至少比目标数组的大小小 1。 由于我们的目标数组的大小可以容纳 2 个元素,因此字段宽度说明符几乎必须为 1。

若要比较字符串,请使用strcmpstrncmp库函数:

if ( strcmp( answer, "y" ) == 0 )
{
// process "y" answer
}

是的,strcmp在匹配项上返回 0。

您还可以与数组中的单个元素进行比较:

if ( answer[0] == 'y' )
{
// process "y" answer
}

记得

如果要从输入流中读取单个字符并将其存储到带有scanf单个字符对象,则可以使用%c转换说明符:

char answer;             // single character, not an array
scanf( " %c", &answer ); // use & operator to obtain pointer, blank skips
// leading whitespace

如果要从输入流中读取一系列非空格字符并将它们存储到带有scanfchar数组中,则可以使用%s转换说明符:

char answer[2];          // array of character
scanf( "%1s", answer );  // do not use & operator to obtain pointer, array
// expressions are converted to pointer expressions
// automatically in this case. 

您需要创建一个缓冲区来存储字符串:

char answer[50]; // change 50 to the maximum length of an answer + 1
scanf("%s", answer);

是的,但您需要为字符串传递缓冲区并使用 strcmp 而不是 == 进行比较。

#include <stdio.h>
#include <string.h>
int main()
{
char answer[16];
printf("Should the crocodile eat the man? yes/no ");
scanf("%15s", answer);
printf("%s", answer);
if (strncmp(answer, "yes", 16) == 0) {
printf("the man is deadn");
} else if (strncmp(answer, "no", 16) == 0) {
printf("the man still aliven");
}
}

最新更新