2016-01-24 58 views
0
cout<<"\n\t Please input the real and the complex part respectively :"; 
if(scanf("%d+i%d",&real_part,&complex_part)!=2) 
{ 
    if(real_part>0) 
     cout<<"\n\t You have entered only the real part"; 
} 

這裏我想掃描一個複數。爲此,上面的代碼工作正常。如果我們輸入單個數字它被指定爲真實部分。但我想,如果我只給i4作爲輸入它將被分配給complex_part保持實部不變(我已經初始化這兩個變量)。有沒有任何可能的方法來實現它?使用多個參數的scanf

回答

1

這個就足夠了:

if(scanf("%d", &real_part) == 1) /* If scanf succeeded in reading the real part */ 
{ 
    if(scanf("+i%d", &complex_part) == 1) /* If scanf succeeded in reading the imaginary part */ 
    { 
     printf("Real part=%d, complex part=%d\n", real_part, complex_part); 
    } 
    else 
    { 
     printf("Real part=%d, complex part=%d\n", real_part, 0); 
    } 
} 
else if(scanf("i%d", &complex_part) == 1) /* If scanf succeeded in reading the imaginary part */ 
{ 
     printf("Real part=%d, complex part=%d\n", 0, complex_part); 
} 
1

函數scanf將返回成功填充的項目數。存儲返回值,並做出一系列的,如果處理每個case語句:

const int filled = scanf(... 
if(filled == 1) 
{ 
    //only real 
} 
else if(filled == 2) 
{ 
    //both 
} 
else 
{ 
    //none, handle error 
}