[英]Can someone help me with structs in C?
任何想法为什么这只是未找到打印。 这个想法当然是用户输入一个名字并打印他们的名字和号码。 当然,任何事情都有帮助。 对不起,我是初学者,我遇到了很多问题。 我选择 C 先学习,希望从这里开始变得更容易。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct
{
char* name;
char* number;
}
person;
int main(void)
{
person people[3];
people[0].name = "sam";
people[0].number = "99912222";
people[1].name = "tom";
people[1].number = "11122222";
people[2].name = "harry";
people[2].number = "12299933";
char boot;
printf("Enter: ");
scanf("%c", &boot);
for(int i = 0; i < 3; i++)
{
if(strcmp(people[i].name, &boot) == 0)
{
printf("%s=%s\n",people[i].name, people[i].number);
return 0;
}
}
printf("Not Found\n");
return 1;
}
尝试:
...
char boot[131] = { }; // name + LF + NULL = 131
printf("Enter: ");
fgets(boot, 130, stdin);
boot[strcspn(boot, "\n")] = '\0'; // remove LF, as we don't need it
if (strlen(boot) > 128) {
printf("ERROR: Name cannot be larger than 128 characters.\n");
return 1;
}
// i < n is a good habit, because sometimes people use
// sizeof on pointers by mistake
for(int i = 0; i < 3; i++)
{
if(strcmp(people[i].name, boot) == 0)
{
printf("%s=%s\n",people[i].name, people[i].number);
return 0;
}
}
printf("Not Found\n");
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.