2017-02-22 79 views
1

我对编程有点新,并且无法确定整个代码为什么一次运行。我如何制作它,以便一次向用户提供一件事?我确定这件事很简单,但我一定已经忘记了。谢谢。程序每次运行一行

#include<iostream> 
using namespace std; 

int main() 
{ 

    int length; 
    int width; 
    int height; 
    int numberCoats; 
    int squareFeet; 
    int name; 
    int paintNeeded; 
    int brushesNeeded; 
    int coatsPaint; 
    int gallonsPaint; 

    cout << "Welcome to the program! What is your first name? \n"; 
    cin >> name; 


    cout << name << " What is the length of the house?"; 
    cin >> length; 


    cout << name << " What is the width of the house?"; 
    cin >> width; 


    cout << name << " What is the height of the house?"; 
    cin >> height; 

    cout << name << " How many coats of paint will it need?"; 
    cin >> coatsPaint; 


    squareFeet = length * width * height; 
    paintNeeded = squareFeet/325; 
    brushesNeeded = squareFeet/1100; 
    gallonsPaint = coatsPaint * paintNeeded; 

    cout << name << " , the amount of square feet is " << squareFeet << endl; 
    cout << name << " , the amount of coats of paint you will need is " << coatsPaint << endl; 
    cout << name << " , you will need " << gallonsPaint << " of paint" << endl; 
    cout << name << " , you will need " << brushesNeeded << " of brushes" << endl; 

        system("pause"); 
        return 0; 
} 
+0

'name'是一个'int'。这听起来不对。你是否输入了'name'的字符串? –

+0

啊好赶上,你是正确的我马上解决这个问题 – Chad

+0

另外,如果你使用字符串,你需要'#包括'在你的标题 – Rime

回答

0

当你进入(例如)Chad您的姓名,该cin >> name失败因为name是不可或缺的类型,而不是一个字符串类型。

这意味着Chad将留在输入流中,所有其他cin >> xx语句也将失败(因为它们也是整型)。

如果你要输入您的姓名作为7,你会发现它工作得很好,除了这不是你的名字:-)

一个更好的解决办法是改变namestd::string和使用的事实getline()阅读它:

#include <string> 

std::string name; 

getline(cin, name); 

使用getline()的原因而不是cin >>是因为后者将停在白色空间,而前者将获得整条生产线。

换句话说,输入Chad Morgan仍然存在您目前所看到的问题,因为它会接受Chad作为您的名字,并尝试将Morgan作为您家的长度。

+0

感谢您的详细解释。对此,我真的非常感激。该计划现在像一个魅力。 getline是有道理的,我会开始使用它,也许它会掩盖这样的愚蠢错误:)。 – Chad

+0

@Chad已经扩展了'getline(cin,somestring)'到'cin >> somestring'的理由。 – paxdiablo

+0

感谢您的扩展。 – Chad