2014-01-18 33 views
0

我試圖掃描for循環中的用戶輸入,除了循環的第一次迭代之外,需要2段數據才能繼續下一步,而且我不理解爲什麼。我會在下面顯示我的代碼,但作爲一個頭,我真的很新,並不是很好,我甚至不確定我使用的方法是否最有效。從for循環中的用戶輸入掃描

#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的速度時它需要兩個值

+0

scanf(「%lf%* c」,&v [temp]);可能解決問題。 – Dipto

+1

是的你是正確的,我的不好,我猜測不徹底檢查舊帖子! – Carterini

回答

0

取出每個格式後的空白"\n"

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

的空白引導scanf()"\n""%lf"後繼續掃描和消耗白空間(例如' ''\n''\t''\r'並且通常4個其他),直到非空白char是找到。這將消耗輸入'\n'尋找更多的空白。

由於stdin通常被緩衝,所以需要輸入整個下一行,然後scanf("\n")才能看到它。

一旦scanf("\n")遇到非空白,它把它放回至stdin下一個 I/O操作。


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 

以下確實消耗double之後的字符,這是通常的輸入,而造成應該像「45年1月23日」輸入發生錯誤句柄挑戰。

// scanf("%lf\n", &m[tmp]); 
scanf("%lf%*c", &m[tmp]); // Not recommended. 

無論代碼路徑採取的,總是一個好主意,檢查的scanf()/sscanf()/fcanf()的結果,尤其是閱讀double時。


的空白指令" ""\n""\t"等所有行爲相同。格式字符串中的任何空白指令都會消耗任何空白。

// All work the same.  
scanf("%lf\n", &v[tmp]); 
scanf("%lf\t", &v[tmp]); 
scanf("%lf ", &v[tmp]);