如果基于用户输入的语句

问题描述:

我想根据用户输入使用不同的if语句。但它似乎只使用最终的设置。任何帮助将非常感谢。如果基于用户输入的语句

char type[20]; 
double weight; 
double feed; 


cout<< "Enter horse type: "; 
cin>>type; 
cout << "Enter the horse weight in whole pounds: "; 
cin>>weight; 
cout<<"Horse type: "<<type<<endl; 
cout<<"Horse weight: "<<weight<<endl; 

这是我的if语句。再次

{ 
    if (type=="Light"); 
    if (weight >= 840 && weight <=1200) 
    feed = (3.0); 
    else if (weight< 840) 
    feed = (3.3); 
    else if (weight > 1200) 
    feed = (2.5); 
    } 
    { 
    if (type=="Large"); 
    if (weight >= 1100 && weight <=1300) 
    feed=(3.0); 
    else if (weight < 1100) 
    feed=(3.3); 
    else if (weight > 1300) 
    feed= (2.5); 
    } 
    { 

    if (type=="Draft"); 
    if (weight >= 1500&& weight <=2200) 
    feed = (3.0); 
    else if (weight< 1500) 
    feed = (3.3); 
    else if (weight >2200) 
    feed= (2.5); 
    } 

    cout<<"Feed Amount "<<feed<<" pounds"<<endl; 

感谢所有帮助

+0

使用正确的缩进方式可以更容易地阅读 – 2014-10-07 01:06:46

+0

如果在第一个if之后使用else,则使用else也是传统的方法,用于块互斥。 – user3344003 2014-10-07 01:13:54

你不能比较使用== C风格字符串(字符数组)。这比较了数组的地址,而不是它们的内容。

改为使用std::string。与

std::string type; 

替换第一行你也需要修复的if声明:

if (type == "Whatever") // no ; 
{ 
    // do stuff 
} 
+0

感谢您的帮助,我将它与您和Matt的答案相结合。再次感谢 – mks 2014-10-07 01:22:49

如果您有:

{ 
if (type=="Light"); 

应该是:

if (type == "Light") 
{ 

和D相同筏和大。无论if如何,您实际上所做的都是不采取任何行动,并始终执行以下代码。

另外(如Mike Seymour所述)将char type[20];更改为std::string type;。如果你真的必须坚持char,那么你也需要改变你的比较。

如果你的编译器支持C++ 14则:

if (type == "Light"s) 

否则:

if (type == std::string("Light")) 

对于任何一种情况下,你需要#include <string>在你的文件的顶部。

+0

谢谢你的工作。 – mks 2014-10-07 01:23:10