![](/img/trans.png)
[英]Are .dll files loaded once for every program or once for all programs?
[英]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
將失敗,因為name
是整數類型,而不是字符串類型。
這意味着Chad
將留在輸入流中,所有其他cin >> xx
語句也將失敗(因為它們也是整數類型)。
如果你輸入你的名字為7
,你會發現它的工作正常,除了不是你名字的事實:-)
更好的解決方案是將name
更改為std::string
並使用getline()
來讀取它:
#include <string>
std::string name;
getline(cin, name);
使用getline()
而不是cin >>
的原因是因為后者將停在白色空間而后者將獲得整行。
換句話說,進入Chad Morgan
仍然會遇到你目前看到的問題,因為它會接受Chad
作為你的名字並試圖讓Morgan
成為你的房子長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.