2017-02-22 81 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