首页 > 解决方案 > 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 块。

标签: cif-statement

解决方案


您对 == 运算符的作用有一个基本的误解。

它不比较字符串。它比较指针。如果你写

char a[100] = "Hello";
char b[100] = "Hello";

然后 a == b 比较指针。a是指向数组a的指针,b是指向数组b的指针,指针不同,比较为假。

使用 strcmp。

PS。仅此一项不会使您的代码工作,因为您正在嵌套块中创建名为“typename”的第二个变量。它是与外部块中的 typename 不同的变量,因此这将没有任何有用的效果。


推荐阅读