首页 > 解决方案 > 无法在数组中存储任何值

问题描述

我无法将值放在数组的第一个元素中。它总是要求将值放在数组的第二个元素中。

#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;
}

标签: arrayscstring

解决方案


由于scanf留下了一个悬空的换行符\n,它会导致gets(Use fgets) 不等待用户的输入。尝试使用getchar.

更新:添加了删除\nfgets

#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;
}

参考:

  1. 删除 scanf 跳过的换行符
  2. 删除 fgets 注册的换行符

推荐阅读