arrays - 无法在数组中存储任何值
问题描述
我无法将值放在数组的第一个元素中。它总是要求将值放在数组的第二个元素中。
#include<stdio.h>
#include<string.h>
int main(void)
{
int a, i;
char names[50][50];
printf("\nEnter the number of names you want :");
scanf("%d", &a);
for(i = 0; i < a; i++)
{
printf("\n%d name :", i);
gets(names[i]);
}
printf("\nThe required name lists :");
for(int i = 0; i < a; i++)
{
printf("\n%d name :", i+1);
puts(names[i]);
}
return 0;
}
解决方案
由于scanf
留下了一个悬空的换行符\n
,它会导致gets
(Use fgets
) 不等待用户的输入。尝试使用getchar
.
更新:添加了删除\n
由fgets
#include<stdio.h>
#include<string.h>
int main()
{
int a,i;
printf("Enter the number of names you want: ");
scanf("%d",&a);
//Flush the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
char names[50][50];
for(i=0;i<a;i++)
{
printf("%d name: ",i);
fgets(names[i],50,stdin); //Use fgets instead of gets
// To remove th \n registed by the fgets
char *p;
if ((p = strchr(names[i], '\n')) != NULL)
*p = '\0';
}
printf("The required name lists: \n");
for(int i=0;i<a;i++)
{
printf("%d name: ",i+1);
puts(names[i]);
}
return 0;
}
参考:
推荐阅读
- javascript - 单击以使用JS将相同的类添加到不同的元素后删除类
- google-cloud-platform - 为什么 PubSub 在确认时会重新发送消息?
- c++ - 使用双指针传递 2D 常量数组
- python - 气流 - Python 脚本在触发时不执行
- java - 自建http服务器无法处理邮递员请求
- node.js - Mongodb、Nodejs 和 Angular 6 中的触发和存储过程
- mongodb - 用于编辑 MongoDB 配置文件的 Bash 脚本
- java - 避免未初始化的非最终成员类/类变量
- php - php用单个数字替换连续相同的多个数字
- mysql - Laravel 无法进行任何迁移。SQL 42000 错误。迁移刷新、重置、回滚无济于事