【问题标题】:C++ Noobie - Why does moving these lines break my application?C++ Noobie - 为什么移动这些行会破坏我的应用程序?
【发布时间】: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 &gt;&gt; hadLiquour?

标签: c++


【解决方案1】:

试试这个

    // 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;

【讨论】:

    【解决方案2】:

    totalBill 是一个数字,即程序“消耗”您输入的所有数字。假设您输入了:

    42.2[返回]

    42.2 被复制到totalBill。 [RETURN] 不匹配,并保留在输入缓冲区中。

    现在,当您拨打getline() 时,[RETURN] 仍然坐在那里...我相信您可以从那里找出其余的。

    【讨论】:

      【解决方案3】:

      Cin 不会从流中删除换行符或进行类型检查。因此,使用cin&gt;&gt;var; 并使用另一个cin &gt;&gt; stringtype;getline(); 将收到空输入。最佳做法是不混合来自 cin 的不同类型的输入法。

      [更多信息见link]

      您可以如下更改您的代码:

      cout << "Please enter your total bill\t";
      getline(cin, hadLiquour);          // i used the hadLiquour string var as a temp var 
                                         // so don't  be confused
      stringstream myStream(hadLiquour);
      myStream >> totalBill;
      

      【讨论】:

        猜你喜欢
        • 2011-05-06
        • 1970-01-01
        • 2021-05-18
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多