【发布时间】:2021-04-27 19:59:09
【问题描述】:
我正在编写 HackerRank 30 天代码中的第 8 天,我遇到了 strcmp 的问题。
该代码询问用户姓名和他们的号码,然后询问其他姓名,如果之前没有输入姓名,则输出Not found,但如果是,则输出姓名和他的号码。但由于某种原因,输出仅在for 语句的最后一个循环中有效。
代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
scanf("%i", &n);
} while (n < 1 || n > 100000);
int i = 0;
phonebook people[n];
for (i = 0; i < n; i++) {
scanf("%s %i", people[i].name, &people[i].number);
}
char othernames[n][100];
for (i = 0; i < n; i++) {
scanf("%s", othernames[i]);
}
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
} else {
printf("Not found\n");
}
}
return 0;
}
【问题讨论】:
-
strcmp(othernames[i], people[i].name)不应该有第二个循环,以便将每个othernames与每个people[].name进行比较? -
char othernames[100][n];应该是char othernames[n][100]; -
%s扫描单个空格分隔的单词。你确定每个名字只有一个词吗? -
或者为什么要存储
othernames的整个列表?除了将其与电话簿进行比较外,您不需要任何给定的空间,因此在阅读后立即将每个电话簿与电话簿进行比较,然后为下一个重新使用相同的空间,会更节省内存并且不会更复杂.