【发布时间】:2012-05-19 20:10:49
【问题描述】:
这是我第一次尝试 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;
}
这很好用。但是,我想搬家:
cout << "Please enter your total bill\t";
cin >> totalBill;
成为下面的第一行:
// Capture inputs
但是当我执行应用程序中断时(它会编译,但只是忽略 if 语句,然后同时打印两个 cout。
我摸不着头脑,因为我不明白发生了什么——但我假设我是个白痴!
谢谢
【问题讨论】:
-
当然你不是白痴:) 我怀疑 hadLiquour 末尾有一个换行符,这就是它不匹配的原因。尝试使用调试器进行调查,或者只是将值输出到屏幕上。如果是这样,您可以重新修改它以仅比较前 3 个字符,但我不会破坏您制作它的乐趣。
-
打印出
hadLiquour并查看其中包含的内容,这将为您提供一些关于出了什么问题的提示。 -
尽量不要将 getline() 和 cin 混在一起,因为这可能会导致如here 所述的问题
-
你知道,你也可以这样做
cin >> hadLiquour?
标签: c++