2016-03-07 175 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

你会在这里提到你在声明中改变了什么? –