I am checking input and need a way to compare to the actual word 'int'.
Example:
char t[10] = "int";
if (t == 'int'){
printf("We have an integr");
}
I'm not sure if this is possible or not, still learning the ropes of C. Thanks for the help!
您可以使用strcmp来比较文本。请注意,它在匹配时返回零:
if (strcmp(t, "int") == 0) {
printf("We have an integer\n");
}
该声明char t[]="int";包括用于使用 with 的空终止符strcmp(),同时在提供int您正在寻找的字符串版本时不使用不必要的内存。
注意:除非您一次检查每个 char 元素,否则使用==运算符将不适用于字符串比较。(见下面的第二个例子)
char t[] = {"int"};
if (strcmp(t, "int")==0){
printf("We have an integr");
}
使用==:
if((t[0]=='i')&&(t[1]=='n')&&(t[2]=='t')&&(t[3]=='\0')){...
也可以
"int"是一个字符串文字。它与所述类型的类型或任何值无关。如果使用原始代码,则int存在完全相同的问题。"foobar"字符串是字符串。
使用'int'(or 'foobar') 也是错误的,因为那些是 [混淆] 字符文字(类型char)而不是字符串文字(类型char*)。编译器应该生成一两个警告 -启用并读取所有警告!- 即使它编译。
最后,请参阅其他答案以了解如何正确比较 C 中的字符串,这解释了为什么该==方法不起作用。