TEL:400-8793-956
当前位置:程序、服务器

如何检查字符串是否符合条件?

提问者:网民 近期获赞:422 浏览人数:366 发布时间:2020-12-09 13:37:53

问:为什么当我需要从用户那里检查字符串时,如果条件不起作用?

 
#include <stdio.h>
main()
{
    char a;
    printf("Enter the Name\n");
    scanf("%d",&a);
 
    if(a=='xyz')
    {
        printf("You enter xyz");
    }
 
    if(a=='abc')
    {
        printf("You enter abc");
    }   
}
 
 
我也尝试了这个,但是甚至不起作用
 
#include <stdio.h>
main()
{
    char a;
    printf("Enter the Name\n");
    scanf("%c",&a);
 
    if(a=='xyz')
    {
        printf("You enter xyz");
    }
 
    if(a=='abc')
    {
        printf("You enter abc");
    }
}
 
答:Jonathon有一个正确的想法,但是即使您正确地从用户那里读取了字符串,您也不能只使用“ ==”来比较两个字符串-它要做的就是将可变字符
 
串地址与固定字符串地址进行比较,并且永远不会匹配。
 
您需要查看使用strcmp [ ^ ]来比较字符串内容:
 
if (strcmp(a, "xyz") == 0)
   {
   ...
   }
 
答:引用:
字符
printf(“输入名称\ n”);
scanf(“%c”,&a);
 
改成
 
char a[256];
printf("Enter the name\n");
fgets(a, 256, stdin);
 
引用:
if(a =='xyz')
{
printf(“您输入xyz”);
}
if(a =='abc')
{
printf(“您输入abc”);
}
改成:
 
if (strcmp(a, "xyz") == 0)
{
  printf("You entered xyz\n");
}
else if (strcmp(a, "abc")==0)
{
  printf("You entered abc\n");
}
 
 
您也可以简单地写:
 
printf("You entered %s\n", a);
 
 
请注意,必须包含string.h才能使用strcmp。
 
 
 
 
[更新]
是的,我忘记了“烦人的换行符未被fgets丢弃”。尝试:
 
#include <stdio.h>
#include <string.h>
int main() {
  char a[256]={0};
  int len;
  printf("Enter the Name\n");
 
  if ( fgets(a,256,stdin) )
 
  // replace the possibly 'not-discarded' newline with string terminator
  len = strlen(a);
  if (len>0 && a[len-1]=='\n')
    a[len-1]='\0';
 
  if (strcmp(a, "xyz") == 0)
  {
    printf("You entered xyz\n");
  }
  else if (strcmp(a, "abc")==0)
  {
  printf("You entered abc\n");
  }
  printf("'%s'\n", a);
  return 0;
}
上一篇: Web.Config的“添加”部分中的Img标记
下一篇: 使用Asp.net的C#中的Next按钮