c - if/else 语句未验证数据
问题描述
我正在编写代码以更好地理解 if/else 语句,但在尝试验证(?)字符串时遇到问题,感谢您的帮助(C 语言)
#include <stdio.h>
#include <stdlib.h>
int main(){
char nametype[100];
printf("Enter the name type (firstname/lastname): ");
scanf("%s", &nametype);
script1(nametype);
return 0;
}
void script1(nametype){
char firstname[100];
int age;
char typename[100];
if(nametype == "firstname"){
char typename[100] = "first name.";
}
if(nametype == "lastname"){
char typename[100] = "last name.";
} else {
printf("You must enter the correct parameters! \n");
main();
}
printf("Enter your name: ");
scanf("%s", &firstname);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hey! Your %s is %s, you're %d \n", typename, firstname, age);
}
在第一个输入中输入“名字”或“姓氏”后,我希望代码继续进行到最后,但它总是继续进入 else 块。
解决方案
您对 == 运算符的作用有一个基本的误解。
它不比较字符串。它比较指针。如果你写
char a[100] = "Hello";
char b[100] = "Hello";
然后 a == b 比较指针。a是指向数组a的指针,b是指向数组b的指针,指针不同,比较为假。
使用 strcmp。
PS。仅此一项不会使您的代码工作,因为您正在嵌套块中创建名为“typename”的第二个变量。它是与外部块中的 typename 不同的变量,因此这将没有任何有用的效果。
推荐阅读
- html - 如何始终保持与粘性页脚聊天?
- python - Python 3 给出错误 Unresolved reference 'long'
- mysql - 为每个员工获得最高薪水
- python - 使用 Python 执行 bcp 将查询从远程服务器导出到本地驱动器
- android - 如何将 WCHAR_T* 转换为 jstring?
- android - Android 应用程序链接:Xamarin 应用程序未在 https URI 上打开
- mongodb - 从聚合 mogodb 中的对象创建数组
- asp.net - 无法使用 CopyTo(Datastream) 在 asp.net 核心中保存图片
- python - 为什么 OpenCV SimpleBlobDetector 不能检测到这张图片中的斑点?
- php - 通过 Laravel 中的中间件转发请求