【发布时间】:2019-06-24 14:27:42
【问题描述】:
我正在尝试获取存储在字符串数组中的名称作为用户输入。当我这样做时,程序会在数组的开头返回一个空元素,并且不会存储用户输入的最后一个元素。
如果我将for 循环中的条件更改为<= size,则代码有效,但我仍然想了解空元素的来源。 This is what I get when I run the code
#define MAXNAME 81
int main() {
int size, i;
printf("Input the number of names in the array: ");
scanf("%d", &size);
// we scan the elements to be stored in the array
printf("Enter %d names to the array:\n", size);
char names[size][MAXNAME];
for (i = 0; i < size; i++) {
gets(names[i]);
}
printf("\n");
// we print the elements stored in the array
int p;
printf("The elements in the array are:\n");
for (p = 0; p < size; p++) {
printf("names[%d] = %s\n", p, names[p]);
}
printf("\n");
// we search for the max length of the elements in the array
int maxLength = 0;
int j, k;
for (j = 0; j < size; j++) {
int testLength = strlen(names[j]);
printf("The length of %s is %d\n", names[j], testLength);
if (testLength > maxLength) {
maxLength = testLength;
}
}
printf("\n");
printf("The maximum length is %d\n", maxLength);
// we print the elements with size == max length
printf("The element(s) with this length is(are):\n");
for (k = 0; k < size; k++) {
int compareLength = strlen(names[k]);
if (compareLength == maxLength) {
printf("%s\n", names[k]);
}
}
return 0;
}
【问题讨论】:
-
您正在读取换行符(在输入数字之后),就好像它是第一个空名称一样。 (另外,不要使用
gets()- 它不能安全使用,应该被视为不可用)。 -
gets() 是许多诸如此类问题的主要原因。使用 scanf() 而不是 gets() 更安全,可以避免这种烦人的错误信息。
-
您的输出是纯文本。请不要添加文字截图。相反,只需将文本复制并粘贴到问题中即可。此外,不应该需要指向外部资源的链接来获取您问题的所有必要细节。
标签: c arrays string input element