C语言基础学习班:用C语言编写一个程序来读取和打印一个班的n个学生的名字

关于C语言基础学习班的问题,在write a program to中经常遇到, 我知道这似乎是一个非常简单的问题,但直到我没有得到所需的输出。请纠正任何错误,因为我第一次在这个网站上发布问题。

我知道这似乎是一个非常简单的问题,但直到我没有得到所需的输出。请纠正任何错误,因为我第一次在这个网站上发布问题。

我尝试的代码如下:

#include<stdio.h>
int main()
{
    int i, n;
    char name[20][80];
    printf("\nEnter the number of students: ");
    scanf("%d", &n);
    printf("\nEnter the name of the students: ");
    for(i=0; i<n; i++)
    {
        fgets(name[i], 80, stdin);
    }
    printf("\nThe name of the students are: \n");
    for(i=0; i<n; i++)
    {
        puts(name[i]);
    }
    return 0;
}

但输出是这样的:

Enter the number of students: 3
Enter the name of students: Park Jimin
Jeon Jungkook 
The name of the students are:
Park Jimin
Jeon Jungkook 

我不明白为什么学生的数量变成了 2,虽然我提到了 3。请帮助。

1

不要使用scanf函数系列-根据我的经验,它们会导致更多的问题,而不是它们解决的问题。在这种情况下,问题是scanf在您输入学生人数后在缓冲区中留下换行符(\ n)字符,因此在您的程序第一次尝试获取学生姓名时会读取空白行。以下内容应该可以成功解决您的作业问题:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
  {
  int i, n;
  char buf[20];
  char name[20][80];
  
  printf("Enter the number of students: ");
  fgets(buf, sizeof(buf), stdin);
  n = atoi(buf);
  for(i=0; i<n; i++)
    {
    printf("Enter student name #%d: ", i+1);
    fgets(name[i], 80, stdin);
    name[i][strlen(name[i])-1] = '\0';  /* overwrite the trailing \n */
    }
  printf("\nThe names of the students are:\n");
  for(i=0; i<n; i++)
    printf("name[%d] = \"%s\"\n", i, name[i]);
  return 0;
  }
OnlineGDB test here
0

而不是使用 fgets 和 puts 使用 scanf 和 printf 如的代码所示。的代码工作我检查了它。你可以改变它,因为你想显示像回车等

int i, n;
      char name[20][80];
      printf("\nEnter the number of students: ");
      scanf("%d", &n);
      printf("\nEnter the name of the students: ");
      for(i=0; i<n; i++)
      {
          //fgets(name[i], 80, stdin);
          scanf("%s",name[i]);
          printf("%d",i);
      }
      printf("\nThe name of the students are: \n");
      for(i=0; i<n; i++)
      {
          //puts(name[i]);
          printf("%d%s",i,name[i]);
      }
      return 0;
0

从我的 pov,这里的问题是输入缓冲区中的一个意外的换行符。虽然这种行为是已知的,有两种不同的方法来解决这个问题。

1.清理您的输入:简单地读取数据并处理这些数据通常是一个坏主意。因此,您可能需要检查您刚刚获得的数据是否有意义并且在您的期望之内。在您的示例中,无论来自缓冲区工件还是真实的用户输入,您都不应该接受空名称。

int j = 0;
while(j<n)
{
    printf("Write to index: %d", j);
    fgets(name[j], 80, stdin);
    if (name[j][0] != '\n')
        {
            j++;
        }
}
https://onlinegdb.com/Hy5ZDWq0U

printf ("Write to index:% d",j) 很容易向您显示的换行符仍然存在,但由于我们的输入检查,它将在下一个循环执行中被覆盖。

2.尝试清除缓冲区:另一种方法是清除缓冲区,以便在调用 fgets 或类似函数之前获得已知的先决条件。在Using fflush(stdin)中,您可以找到一个关于如何出错以及为什么这样做相当脆弱的讨论。

就我个人而言,我总是更喜欢第一个解决方案,因为您的代码应该负责根据其需求处理意外的输入。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(405)
Wish list:使用Wish应用程序打开Tcl文件
上一篇
Case a:对一个switchcase语句使用两个值
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(80条)