程序一次运行每一行

时间:2017-02-22 05:07:47

标签: c++

我对编程有点新意,并且无法弄清楚整个代码一次运行的原因。如何制作它以便一次向用户询问一件事?我确定它很简单但我必须忘记它。感谢。

#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;
}

1 个答案:

答案 0 :(得分:0)

当您输入(例如)Chad作为您的名字时,cin >> name失败,因为name是整数类型,而不是字符串类型。

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

如果您输入的姓名为7,那么您会发现它的工作正常,而不是您的名字: - )

更好的解决方案是将name更改为std::string并使用getline()将其读入:

#include <string>

std::string name;

getline(cin, name);

使用getline()而不是cin >>的原因是因为后者将停留在空格上,而前者将获得整行。

换句话说,输入Chad Morgan仍然会遇到您当前看到的问题,因为它会接受Chad作为您的姓名并尝试获取Morgan作为您的房屋长度