【问题标题】:Fgets skipping input and printing next line?Fgets跳过输入并打印下一行?
【发布时间】:2014-03-24 02:38:48
【问题描述】:

我正在尝试读取包含空格的字符串,因此 scanf 无法正常工作,因此我正在尝试使用 fgets。当我运行它并点击 if 语句时,屏幕上打印的是:

Please enter the course name.
You entered the course: 


Please enter the course ID.

=========================

if(coursetotal==0)/*start of 1 course*/
    {

        printf("Please enter the course name.\n");
        fgets(course[0].name,sizeof(course[0].name),stdin);
        printf("You entered the course name: %s\n",course[0].name);


        printf("\nPlease enter the four digit course ID.\n");
        int temp=0,temp1=0,count=0; /*Variables used to check if 4 digits*/
        scanf("%d",&temp);
        temp1=temp;
        while(temp1!=0)
        {
            temp1/=10;
            count++;
        }
        if(count==4)/*start of is 4 digits*/
        {
            course[0].id=temp;
            coursetotal+=1;
            printf("You entered the course ID: %d\n",course[0].id);
        }/*end of is 4 digits*/
        else
        {
            printf("The course ID you input was not 4 digits.\n");
            return;
        }

        printf("You have successfully added the course: %s. The ID is : %d, and you now have a total of %d course.\n",course[0].name,course[0].id,coursetotal);

    } /*end 1 course*/

【问题讨论】:

  • 因为在开始时 sizeof(course[0].name) 为 0,所以它不占用任何字符............从以下位置读取 fgets() 函数tutorialspoint.com/c_standard_library/c_function_fgets.htm
  • 您可能在之前的用户交互中在输入队列中留下了换行符。尝试在fgets 之前调用getchar 作为测试。真正的解决方案取决于您如何处理之前的交易。
  • @JatinKhurana sizeof() 怎么可能返回零?
  • 不如先检查一下你的 api 函数结果。 C 编程的The Sixth Commandment 从小就应该认真对待,初学者代码中最常见的错误常常归因于天真的假设,即如果某些东西通常有效,它就会永远有效。
  • 避免将scanf()fgets() 混合使用。正如@user3386109 所说,您有来自scanf() 等的剩余\n。使用fgets()sscanf()strtol() 读取整数。

标签: c fgets


【解决方案1】:

首先我必须解决我在这里看到的问题:

我正在尝试读取包含空格的字符串,因此 scanf 不起作用

That's not true at all. 有一种叫做negated scanset 的东西,您可以使用它来读取通常终止scanf()s 字符串输入的空白​​字符(例如空格)。

就是这么说的。你真的应该只选择一种输入机制scanf()fgets() 并专门使用它。当你混合时,事情会变得奇怪和错过。您在这里完成的事实告诉我您已经在其他地方完成了它,并且您可能在此之前使用了scanf(),从而为自己留下了一个“不干净”的stdin 缓冲区。这将解决您的问题。


现在只是一个简单的例子,给定一个 int (num) 和一个 char * (`string):

scanf("%d", &num);
fgets(string, sizeof(string), stdin);
printf("%d\n%s\n", num, string); 

您似乎会跳过为fgets 输入任何内容的功能,因为它实际上只是从scanf() 的数字条目中提取了换行符。您会在输出中看到如下内容:

5
5
               // <-- and a couple
              //  <-- of blank lines

表示您选择了换行符。如果您要查看字符串的第一个(也是唯一一个)字符的 ASCII 值,则更加明显:

printf("%d\n", string[0]);   // this would yield 10 the ASCII value of \n

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多