字符串比较里面如果条件失灵 [英] string comparison inside if condition malfunctioning
问题描述
if(char)
中匹配多个字母。它显示以下错误信息(在linux终端中使用gcc):lockquote
main.c main.c main.c main.c: 16:23:警告:字符常量
对于其类型[默认启用]太长
if(firstName [20] =='Vojta'){
源代码:
#include< stdio.h>
int main(int argc,char const * argv [])
{
/ * code * /
char firstName [20];
char lastName [40];
char password [20];
char confpasswd [20];
int age;
printf(请写下你的名字和姓氏:);
scanf(%s%s,firstName,lastName);
printf(%s%s:\ n,firstName,lastName);
if(firstName [20] =='Vojta'){
printf(\\\
cool\\\
);
}
返回0;
/ strong>
使用 strcmp()
来比较字符串。
第2点
$ b
更改
scanf(%s%s,firstName,lastName);
至
scanf(%19s%39s,firstName,lastName);
和 do 检查 scanf的返回值()
以确保成功。但是,如果您单独使用两个 scanf()
来接受两个输入,那么错误容易 会更好。
$ b
此外,作为建议,您可以阅读有关 fgets()
和 strtok()
为方法阅读整行作为输入和标记化所需的部分。
I tried to program in C but was not sucessful. I have a simple source code and I need to match multiple letters in if (char)
. It's displaying the following error message (in linux terminal using gcc):
main.c: In function `main': main.c:16:23: warning: character constant too long for its type [enabled by default]
if (firstName[20] == 'Vojta'){
Source code:
#include <stdio.h>
int main(int argc, char const *argv[])
{
/* code */
char firstName[20];
char lastName[40];
char password[20];
char confpasswd[20];
int age;
printf("Please write your first and last name:");
scanf("%s%s", firstName, lastName);
printf("%s %s:\n", firstName, lastName);
if (firstName[20] == 'Vojta'){
printf("\ncool\n");
}
return 0;
}
Point 1
Use strcmp()
to compare strings.
Point 2
Change
scanf("%s%s", firstName, lastName);
to
scanf("%19s %39s", firstName, lastName);
and do check the return value of scanf()
to ensure sucess. However, it's better if you use two scanf()
seperately to take two inputs, that will be less error prone.
Also, as a suggestion , you can read about fgets()
and strtok()
for a how-to read a whole line as input and tokenize the required part.
这篇关于字符串比较里面如果条件失灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!