gpt4 book ai didi

C++ Noobie - 为什么移动这些行会破坏我的应用程序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:53 24 4
gpt4 key购买 nike

这是我对 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。

我抓耳挠腮,因为我不明白发生了什么 - 但我假设我是个白痴!

谢谢

最佳答案

试试这个

    // Capture inputs
cout << "Please enter your total bill\t";
cin >> totalBill;
cin.clear();
cin.sync();

参见 c++ getline() isn't waiting for input from console when called multiple times

或者,最好根本不使用 getline:

cout << "Please enter your total bill\t";
cin >> totalBill;

cout << "Did you drink any booze? (Yes or No)\t";
cin >> hadLiquour;

关于C++ Noobie - 为什么移动这些行会破坏我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com