运行 for 循环与 scanf 函数的正确方法是什么

what is the proper way of running for loop with scanf function

我刚开始学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 正在重新显示时,它没有显示字符串 "enter the %d position" 它直接要求值。

你的 scanf 不需要 space 和换行符,只需要 "%d".

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

快速解决您的问题:scanf("%d \n",&a[i]) -> scanf("%d",&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 是一个不错的选择 前提是 输入的格式与您期望的格式完全相同。这使得它成为用户输入的糟糕选择,因为用户是非常不可预测的。

这里有一个 link 值得一读:

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

您可以像下面这样使用:

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