这是我第一次尝试使用C++,下面是一个通过控制台应用程序计算提示的示例.完整(工作代码)如下所示:
// Week1.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// Declare variables
double totalBill = 0.0;
double liquour = 0.0;
double tipPercentage = 0.0;
double totalNoLiquour = 0.0;
double tip = 0.0;
string hadLiquour;
// Capture inputs
cout << "Did you drink any booze? (Yes or No)\t";
getline(cin, hadLiquour, '\n');
if(hadLiquour == "Yes") {
cout << "Please enter you booze bill\t";
cin >> liquour;
}
cout << "Please enter your total bill\t";
cin >> totalBill;
cout << "Enter the tip percentage (in decimal form)\t";
cin >> tipPercentage;
// Process inputs
totalNoLiquour = totalBill - liquour;
tip = totalNoLiquour * tipPercentage;
// Output
cout << "Tip: " << (char)156 << tip << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这很好用.但是,我想移动:
cout << "Please enter your total bill\t";
cin >> totalBill;
Run Code Online (Sandbox Code Playgroud)
成为第一行:
// Capture inputs
Run Code Online (Sandbox Code Playgroud)
但是当我执行应用程序中断时(它编译,但只是忽略if语句,然后立即打印两个cout).
我抓挠我的头,因为我无法理解发生了什么 - 但我假设我是个白痴!
谢谢
试试这个
// Capture inputs
cout << "Please enter your total bill\t";
cin >> totalBill;
cin.clear();
cin.sync();
Run Code Online (Sandbox Code Playgroud)
多次调用时,请参阅 c ++ getline()不等待来自控制台的输入
或者,更好的是根本不使用getline:
cout << "Please enter your total bill\t";
cin >> totalBill;
cout << "Did you drink any booze? (Yes or No)\t";
cin >> hadLiquour;
Run Code Online (Sandbox Code Playgroud)