程序一次运行每一行
Program runs every line at once
我对编程有点新鲜,并且难以弄清楚为什么整个代码一次运行。我该如何做到这一点,以便一次询问用户一件事?我确定这很简单,但我一定已经忘记了。谢谢。
#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
作为您的房屋长度。
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 我如何使一行代码可以选择,但在已经选择过一次后不重新选择
- 程序一次运行每一行
- 如何将.txt文件中的多维数组放入代码中,并一次打印一行
- 如何强制 getline() 一次输入一行
- 循环每隔一行跳过一次
- 在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题
- 如何一次一个单词而不是一行一行地消除错误输入
- C++:一次阅读一个字符,直到一行的末尾不起作用
- 启动 QProcess 并一次读取一行输出
- 在c++中一次向字符串数组中输入一行
- C/ c++一次读取一行
- 使一行运行一次,文本为基础的游戏