在for循环中扫描用户输入

时间:2014-01-18 13:41:21

标签: c

我正在尝试在for循环中扫描用户输入,除了循环的第一次迭代需要2个数据才能继续下一步并且我不明白为什么。我将在下面显示我的代码,但作为一个抬头我真的是新手并不是很好,我甚至不确定我使用的方法是否最有效。

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

#define     w   1.0
#define     R   1.0

int main(int argc, char *argv[])
{
int     tmp;
double  *x, *v, *m, *k;

x = malloc((argc-1)*sizeof(double));
v = malloc((argc-1)*sizeof(double));
m = malloc((argc-1)*sizeof(double));
k = malloc((argc-1)*sizeof(double));

if(x != NULL)
{
    for(tmp=0; tmp<argc-1; tmp++)
    {
        sscanf(argv[tmp+1], "%lf", &x[tmp]);
    }
}
else
{
    printf("**************************\n");
    printf("**Error allocating array**\n");
    printf("**************************\n");
}

if(argc <= 2)
{
    printf("************************************\n");
    printf("**There must be at least 2 masses!**\n");
    printf("************************************\n");
}
else if(argc == 3)
{
    for(tmp=0; tmp<argc-1; tmp++)
    {
        printf("Input a value for the velocity of Block %d\n", tmp+1);
        scanf("%lf\n", &v[tmp]);
    }

    for(tmp=0; tmp<argc-1; tmp++)
    {
        printf("Input a value for the mass of Block %d\n", tmp+1);
        scanf("%lf\n", &m[tmp]);
    }

    for(tmp=0; tmp<argc-1; tmp++)
    {
        printf("Input a value for the spring constant of Spring %d\n", tmp+1);
        scanf("%lf\n", &k[tmp]);
    }
}
else
{
    for(tmp=0; tmp<argc-1; tmp++)
    {
        printf("Input a value for the velocity of Mass %d\n", tmp+1);
        scanf("%lf\n", &v[tmp]);
    }

    printf("Input a value for the mass of each Block\n");
    for(tmp=0; tmp<argc-1; tmp++)
    {   
        scanf("%lf\n", &m[tmp]);
    }

    printf("Input a value for the spring constant of each Spring\n");
    for(tmp=0; tmp<argc-1; tmp++)
    {
        scanf("%lf\n", &k[tmp]);
        printf("%lf\n", &k[tmp]);
    }
}   
}

所以是的,主要问题是当为块1的速度取值时,它需要两个值

1 个答案:

答案 0 :(得分:0)

在每种格式后删除空格"\n"

// scanf("%lf\n", &v[tmp]);
scanf("%lf", &v[tmp]);

"\n"之后的空格"%lf"指示scanf()继续扫描并消耗空白区域(例如' ''\n',{{1} },'\t',通常还有4个其他内容),直到找到非空白'\r'。这将消耗 Enter char 寻找更多的空白区域。

由于'\n'通常是缓冲的,因此需要在stdin看到任何一行之前输入整个下一行。

scanf("\n")遇到非空格后,会将其重新置于scanf("\n")以进行下一步 I / O操作。


一般来说,

stdin会在输入错误输入时出现挑战。为了可靠地处理恶意用户输入,请考虑使用scanf()组合。 (或fgets()/sscanf()

fgets()/strtod()

以下内容会消耗char buf[50]; double d; if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOForIOError(); if (sscanf(buf, "%d", &d) != 1) Handle_ParseError(); // good to go 之后的字符,通常是 Enter ,但如果输入“1.23.45”,则会产生错误句柄挑战。

double

无论采用何种代码路径,最好检查// scanf("%lf\n", &m[tmp]); scanf("%lf%*c", &m[tmp]); // Not recommended. 的结果,尤其是在阅读scanf()/sscanf()/fcanf()时。


空白空间指令double" ""\n"等都表现相同。格式字符串中的任何空格指令都会占用任何空格。

"\t"