【问题标题】:what is the proper way of running for loop with scanf function [duplicate]使用scanf函数运行for循环的正确方法是什么[重复]
【发布时间】:2018-07-11 04:26:20
【问题描述】:

我刚开始学习 c。我这里有一个代码,用于获取用户的输入并打印出来。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[5];
    int i ;

    for(i=0;i<5;i++)
    {
         printf("enter the %d position no: ",i+1);
         scanf("%d \n",&a[i]);
    }

    for(i = 0;i<5;i++)
        printf("position %d : %d \n",i+1,a[i]);

}

这是我的输出控制台。

但是输出给出了误导性的结果。 在第 2 行,当 scanf 变红时,它没有显示字符串“输入 %d 位置”,而是直接要求值。

【问题讨论】:

标签: c printf scanf c11


【解决方案1】:

您的scanf 不需要空格和换行符,只需"%d"

for(i=0; i<5; i++)
{
     printf("enter the %d position no: ",i+1);
     scanf("%d",&a[i]);
}

【讨论】:

  • 不检查循环中的返回值...
【解决方案2】:

快速解决您的问题:scanf("%d \n",&amp;a[i]) -> scanf("%d",&amp;a[i])

另外,请记住始终检查 scanf 是否有错误。可以这样做:

if(scanf("%d", &a[i]) < 0) {
    // Print error message and/or exit or whatever you want to do
} else {
    // Do something else
}

从长远来看:

花点时间研究一下 C 中的输入法。它们有点棘手,而且存在数百万个陷阱。简而言之,scanf 是一个不错的选择只要输入的格式与您期望的完全相同。这使得它成为用户输入的糟糕选择,因为用户是不可预测的。

这是一个值得一读的链接:

http://www.giannistsakiris.com/2008/02/07/scanf-and-why-you-should-avoid-using-it/

【讨论】:

    【解决方案3】:

    你可以像下面这样使用:

    for(i=0;i<5;i++)
    {
       printf("enter the %d position on : ",i+1);
       scanf("%d",&a[i]);
       printf("\n");
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 2014-06-28
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多