程序一次运行每一行

Program runs every line at once

本文关键字:一行 一次 程序 运行      更新时间:2023-10-16

我对编程有点新鲜,并且难以弄清楚为什么整个代码一次运行。我该如何做到这一点,以便一次询问用户一件事?我确定这很简单,但我一定已经忘记了。谢谢。

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

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

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

如果您要输入您的名字为7,您会发现它可以正常工作,除了不是您的名字的事实: - )

一个更好的解决方案是将name更改为std::string,然后使用getline()在以下内容中读取它:

#include <string>
std::string name;
getline(cin, name);

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

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