假设我们有一个结构体:
struct Person {
char name[50];
int age;
}
现在我们要比较一个来自结构体的字符串和一个来自用户输入的字符串。我们可以使用标准库函数strcmp()
来比较这两个字符串。
例如,我们可以定义一个Person
结构体实例:
struct Person p = {"Tom", 25};
然后我们可以提示用户输入一个字符串,例如:
char input[50];
printf("Please enter your name: ");
scanf("%s", input);
接下来,我们可以使用strcmp()
函数来比较p
的名字和用户输入的名字:
if (strcmp(p.name, input) == 0) {
printf("You have the same name as our person Tom!\n");
} else {
printf("You have a different name.\n");
}
这里的strcmp()
函数返回值为0,表示两个字符串相同。如果返回结果不为0,则表示两个字符串不同。