问题是当我尝试输入一个字符串时,空间编译器将其呈现为单独的 2 个字符串。但要求是每当字符串中有空格时,不要将其视为 2 个字符串,而是一个字符串。只有当我的四个输入是 MAHIRL、CHITRA、DEVI 和 C 时,程序才应该打印 yes。我的代码是:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[10],str2[10],str3[10],str4[10];
scanf("%s",str1);
scanf("%s",str2);
scanf("%s",str3);
scanf("%s",str4);
if(strcmp(str1,"MAHIRL")==0 && strcmp(str2,"CHITRA")==0 && strcmp(str3,"DEVI")==0 && strcmp(str4,"C")==0 ){
printf("yes");
}
else{
printf("no");
}
return 0;
}
我尝试使用 strtok() 和 strpbrk(),但我不太确定如何在我的代码中实现它们。任何帮助或建议表示赞赏。谢谢。
最佳答案
problem is when I try to enter a string with space compiler render that as separate 2 strings
这不是问题,这是 %s
格式说明符与 scanf()
的 特性/行为。您不能使用它读取以空格分隔的输入。
对于转换说明符 s
,章节 §7.21.6.2,C11
s
Matches a sequence of non-white-space characters. [...]
因此,匹配一旦遇到空白字符即结束,此处为 space
。
如果您必须读取行(即输入以换行符 终止),请使用fgets()
相反。
关于c - 在字符串 inC 中搜索空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45281183/