2016-03-07 48 views
-6

我正在編寫一個程序來處理貸款。問題是它只讀取第一個if語句,然後執行讀取"("Thank you,your loan is being processed")"程序的最後一句,我該如何糾正?它跳過評估用戶輸入的部分。這是代碼。C++程序只執行第一個「if」語句

#include<stdio.h> 
#include<sstream> 
#include<iostream> 
#include <conio.h> 
#include <string.h> 


using namespace std; 

int main() { 

char landtitle[100]; 

char Asset[100]; 
//std::string Asset; 

float NumberPlate; 
float Year; 



char L[100]; 
char t[100]; 

float amount; 

float logbook; 
float block; 
float PlotNumber; 

//float InterestRate; 
float LoanAmount; 

//LoanAmount = amount * (1+(15/100))*(1+(15/100)); 
//printf("Amount to be paid after one month is %f",LoanAmount); 


printf("Enter amount you want to borrow"); 
printf("\nWe wil need an asset for any amount greater than 3M:"); 

scanf("%d",&amount); 


if (amount > 3000000) 
{ 
    printf("Please choose Asset(use L for logbook or T for title"); 
    //getline(cin,Asset); 
    gets(Asset); 
    //cin.ignore(); 

    if (Asset == "L") 
    { 
     printf("\nPlease enter logbook number :"); 
     scanf("%f",&logbook); 
     printf("\nPlease enter car Number plate :"); 
     scanf("%f",&logbook); 
     printf("\nPlease enter Year of manufacture :"); 
     scanf("%f",&logbook); 

     //printf("Thank you,your loan is being processed"); 
    } 
    else 
    { 
     printf("\nPlease enter Land title :"); 
     gets(landtitle); 
     printf("\nPlease enter Block :"); 
     scanf("%f",&block); 
     printf("\nPlease enter Plot Number :"); 
     scanf("%f",&PlotNumber); 

     //printf("Thank you,your loan is being processed"); 
    } 



} 

else 
{ 
    printf("Thank you,your loan is being processed"); 
} 


} 
+0

你不應該使用'得到()',其中有緩衝區溢出的風險不可避免。另外C風格的字符串不能通過'=='進行比較,所以應該使用'strcmp()'。 – MikeCAT

+0

@ MikeCAT。我應該用什麼來代替get()來捕獲字符串或char。 – brayo

+2

你正在使用C++,所以'std :: string Asset; std :: getline(std :: cin,Asset);'很好。 – MikeCAT

回答

0
scanf("%d",&amount); 

你要掃描的浮動,而不是一個整數,所以你要%f

0

當你比較陣列中的一個字符串轉換爲字符串字面量,例如像

Asset == "L" 

然後陣列衰減到一個指向它的第一元件,和同樣的事情發生到字符串文字"L"。然後比較指針而不是它們指向的實際字符串。那比較將從來沒有爲真。

要比較C++中的字符串,你應該使用std::string,那麼你可以使用簡單的==進行相等。

如果你想繼續使用C風格的字符串(即數組char),那麼你需要使用strcmp函數。

0

您的金額是浮動的,但您嘗試使用整數讀取。

所以會有轉換成另一個數字。

+0

我對字符串使用了std :: string「name」,但它仍然會跳過它應該輸入「Asset」和「DistrictLocation」這些字符串的部分。我應該如何解決這個問題? – brayo

0

字符串(字符陣列)無法通過在C/C++ ==符號進行比較。因此,當你寫
if (Asset == "L")
它實際上分配給陣列的點的陣列(名稱中的第一個元素的地址進行比較數組)在內存中永遠不會相等的兩個不同的數組,所以條件總是假的。

此行

if (Asset == "L") 

只是改變

if (!strcmp(Asset,"L")) 
+0

錯誤地使用了字符串聲明。關注這裏的建議並找出答案。工作就像魅力。 – brayo

+0

你會在這裏提到你在聲明中改變了什麼? –