#include <stdio.h>
#include <stdlib.h>
int main(){
char name[50];
char *top5[5] = {"user1" , "user2" , "user3" , "user4" , "user5"};
int i ;
for(i=0;i<5;i++){
printf("You entered the top5. Please enter your name: ");
scanf("%s", &name);
top5[i] = name;
}
for(i=0;i<5;i++){
printf("%s" , top5[i]);
}
}
我希望它打印5
不同的名称,因为我使用了 5
运行代码时的不同名称。但它总是打印我使用的姓氏。它打印它 5
次。我该如何修复该代码?
最佳答案
对于初学者来说,根据 C 标准,不带参数的函数 main
应声明为
int main( void )
在循环体中的这条语句之后
top5[i] = name;
数组top5
的每个元素都指向数组name
的第一个字符。
您可以声明一个二维字符数组,而不是使用指针数组。
与格式说明符 %s
一起使用的函数 scanf 是不安全的。此外,参数应指定为 name
而不是 &name
。
您可以使用标准函数fgets
代替scanf
。
这是一个演示程序,展示了如何编写原始程序。
#include <stdio.h>
#include <string.h>
#define N 20
int main( void )
{
char name[N];
char top5[][N] =
{
"user1" , "user2" , "user3" , "user4" , "user5"
};
const size_t M = sizeof( top5 ) / sizeof( *top5 );
for ( size_t i = 0; i < M; i++ )
{
printf("You entered the top5. Please enter your name: ");
fgets( name, sizeof( name ), stdin );
name[ strcspn( name, "\n" ) ] ='\0';
strcpy( top5[i], name );
}
for ( size_t i = 0; i < M; i++ )
{
puts( top5[i] );
}
}
关于c - 为什么这段代码会打印同样的内容 5 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222129/