【问题标题】:C++ Variables Losing Assignment Inside "if" LoopC++ 变量在“if”循环中丢失赋值
【发布时间】:2015-12-09 23:37:06
【问题描述】:

所以我确定这是一个非常简单的问题,但我才刚刚开始。

在程序中,有简单的输入验证。如果输入正确,则没有问题。

问题是,当测试程序出现错误时,例如输入零或负数,输出中的所有变量都是空白(即字符串变为空白,数字变为零)。

提前感谢您的帮助和见解。

// This menu driven program determines the time sound will take to travel through
// gas, liquid, and solid, given a distance from a user.

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
// constants
const double    AIR_SPEED_RATE_PER_SECOND_SOUND = 1100.0,       //in feet per second
                WATER_SPEED_RATE_PER_SECOND_SOUND = 4900.0,     // in feet per second
                STEEL_SPEED_RATE_PER_SECOND_SOUND = 16400.0;    // in feet per second

// Program defined variables
double          Time_To_Travel = 0.0;       // in seconds

string          Medium;

// User defined variables
double          distance_of_travel; //in feet

int             menu_selection;

//Display a menu for mediums of sound conduction.
cout << "Sound travels at different speeds through air, water, and steel." << endl;
cout << "\nThis program will calculate the time it takes, in feet per second, for " \
"sound to travel a given distance." << endl;
cout << "Please select a number choice below:\n\n1. Air\n2. Water\n3. Steel " << endl;

//Get input from user.
cout << "\nEnter Selection: ";
cin >> menu_selection;

cout << "\nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;


// Input validate selection is on the menu
if (menu_selection >= 1 && menu_selection <= 3)
    {
    if (distance_of_travel > 0.0)  // input validation distance is positive
        {
        switch (menu_selection)  // calculate the time of travel based on user input
            {
            case 1: Medium = "air";
                    Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
                break;

            case 2: Medium = "water";
                    Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
                break;

            case 3: Medium = "steel";
                    Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
                break;
            }
        }
    else
        {
        cout << "\nPlease enter a distance greater than zero: ";
        cin >> distance_of_travel;
        }
    }

else
    {
    cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
    cin >> menu_selection;
    }
// Format to four decimal places and display the time sound takes to travel given distance.
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;

return 0;

}

【问题讨论】:

  • 您是否尝试过在调试器中单步执行此代码?
  • 没有if loop 这样的东西。如果你想要一个循环,请使用whilefor
  • 谢谢@Barmar,我会记住的
  • @MrEricSir 我不太清楚如何在 Xcode 中运行调试器。

标签: c++ if-statement nested switch-statement variable-assignment


【解决方案1】:

if 语句是一个简单的分支,而不是循环。在if 结束时,继续执行到块的末尾。

if (menu_selection >= 1 && menu_selection <= 3)

如果为 false,这将跳过程序的核心并跳转到处理无效输入的代码。

else
{
    cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
    cin >> menu_selection;
}

再次输入menu_selection后,控制流向

cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;

永远不会对新输入进行操作,并且会打印未触及的值。将初始的if 替换为包含用户输入的do {...} while(condition); 循环。一旦输入令人满意,您就可以进入程序的核心。

bool is_good;
do
{
    is_good = false;
    cout << "\nEnter Selection: ";
    cin >> menu_selection;
    cout << "\nEnter distance in feet the sound will travel: ";
    cin >> distance_of_travel;
    if (menu_selection < 1 || menu_selection > 3 || distance_of_travel < 0)
        cout << "error message here";
    else
        is_good = true;
} while (!is_good);

【讨论】:

  • @NonCreature0714 我编辑了它以在输入错误时显示。
  • 我对您的出色回答投了赞成票,以表示感谢和感谢。
  • @NonCreature0714 很高兴我能帮上忙!
  • 如果某些聪明人输入了无可救药的无效垃圾,请记得刷新输入缓冲区并清除错误标志。
  • 每当我尝试刷新输入缓冲区时,我都会陷入无限循环。 istream 是我存在的祸根。
【解决方案2】:

您可以通过将default 块添加到您的switch 语句来处理case 块中未定义的零、负数或所有可能的输入。然后您的代码将如下所示。

switch (menu_selection)  // calculate the time of travel based on user input
        {
        case 1: Medium = "air";
                Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
            break;

        case 2: Medium = "water";
                Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
            break;

        case 3: Medium = "steel";
                Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
            break;
        default:
            // handle zero, negative numbers and so on.
            break;
        }

参考:http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm

【讨论】:

  • OP 已经捕获了无效数据(顺便说一句,此解决方案不会捕获无效的 distance_of_travel),但在处理它时遇到了困难。
猜你喜欢
  • 2019-04-30
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2018-04-07
相关资源
最近更新 更多