gpt4 book ai didi

c - 尝试获取用户输入,将输入放入数组中,然后清除输入,以便可以获得更多

转载 作者:行者123 更新时间:2023-11-30 16:42:16 25 4
gpt4 key购买 nike

所以我试图从用户那里获取输入,然后将输入放入数组中,然后清除输入,这样它就可以获得更多,但我得到的只是这些奇怪的符号,这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char source[] = "this is the source string";

int main()
{

char people[5][260];
char input[260];

int i, l;

printf("please enter 5 names\n");

for(i=1;i<6;i++)
{
gets(input);
strcpy(people[1], input);
input[260] = '\0';


}

for(l=0;l<6;l++)
printf("%s\n", people[l]);
}

}

最佳答案

改变

    for(i=1;i<6;i++) 
{
gets(input);
strcpy(people[1], input);
input[260] = '\0';
}

    for(i=0;i<5;i++)
{
gets(input);
strcpy(people[i], input);
input[0] = '\0';
}

现在要清楚的是,我将循环从 0 更改为 5,而不是 1 到 6,因为

array indices start from 0.

在strcpy函数调用中,你一次又一次传递了相同的值,即1,我将其更改为循环变量i,这是正确的方法。

在您的代码片段中,您分配了值 input[260] = '\0'这也是错误的。

'\0' is used to denote the end of a string

所以你必须清空你的字符数组

'\0' should be assigned to the first index of the array to denote that the array is empty.

现在在第二个循环中,由于您已经存储了 5 个名称,因此循环应该来自 i=0i<5而不是i<6

所以改变

for(l=0;l<6;l++)
printf("%s\n", people[l]);

for(l=0;l<5;l++)
printf("%s\n", people[l]);

并且您还在最后一个 printf 语句后使用了额外的大括号。删除它,您的代码就修复了。

由于您使用了 main 函数的返回类型作为 int

int main()

所以它会返回一个整数值,所以

you should use a return statement

像这样在最后一个大括号之前

return 0;

您已声明一个名为 source[] 的字符数组具有全局作用域,但您尚未在代码中的任何位置使用它,因此最好将其删除。

而且也正确

indent your code using white spaces and tabs to make it understandable and readable

,通过代码缩进,您的代码将更具可读性,并且您不会错过任何大括号或使用像在代码中使用的额外大括号。

总结一下,您的新代码将如下所示:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char people[5][260];
char input[260];
int i, l;
printf("please enter 5 names\n");
for(i=0;i<5;i++)
{
gets(input);
strcpy(people[i], input);
input[0] = '\0';
}
for(l=0;l<5;l++)
printf("%s\n", people[l]);
return 0;
}

关于c - 尝试获取用户输入,将输入放入数组中,然后清除输入,以便可以获得更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45900741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com