如何使用两个字符来控制 C++ 程序的流程

How to use two characters to control the flow of a c++ program

本文关键字:C++ 控制 程序 字符 何使用 两个      更新时间:2023-10-16

如何使用两个字符(A 和 B(来控制当用户输入其中任何一个字符时执行代码的哪一部分..?Forexaple当用户输入A时,转到某种交易类型并要求用户输入该交易的信息。如果为 B,则执行其他一些牵引类型,将要求用户输入此类事务的信息。我刚开始学习编程(C++(请..

谢谢

C++作为一种

命令式编程语言,提供了几个控制语句,如if/else,while,switchfor来控制程序的流程。 它们在您目前正在阅读的C++书中进行了解释。

试试这个。

#include <iostream>
int main() {
    char in;
    std::cin >> in;
    switch (in) {
        case 'A':
            // Do something.
            break;
        case 'B':
            // Do something else.
            break;
        default:
            std::cerr << "Invalid character." << std::endl;
            return 1;
    }
}

C++有很多方法可以实现选择结构。

  1. 如果其他(基本上每种编程语言都有(

if (a)
{
    //do something
}
else 
{
    //do something else
}
  1. 开关控制

switch (input)
{
case a:
     // do something
     break;
case b:
     // do something else
     break;
default:
     // default when the user input is not expected a or b
}
  1. 标签和转到关键字

int main(void)
{
    //something....
    if (a) goto label_a;
    else if (b) goto label_b;
label_a:
    //something...
    goto end;
label_b:
    //something else
    goto end;
end:    
    return 0;
}
  1. 函数调用

void first() { /*something*/ }
void second() { /*something else*/ }
int main(void)
{
    //your previous codes
    if (a) 
    {
        first();
    }
    else
    {
        if (b)
        {
            second();
        }
    }
    return 0;
}


更多阅读内容:CPlusPlus 语句和控制
或者你可以投资一些钱买一本好的C++参考书,比如C++ Primer

一种可能的解决方案是:

#include <iostream>
#include <string>
void input_A() {
    //Do things after input A
    std::cout << "You used function A" << std::endl;
}
void input_B() {
    //Do things after input B
    std::cout << "You used function B" << std::endl;
}
void input_recv(std::string input)
{
    // Use if condition or switch statement for input evaluation
    if (input == "A"){
        input_A();
    }
    else if(input == "B"){
        input_B();
    }
    else {
        std::cout << "No valid input" << std::endl;
    }
}
int main()
{
    std::string input = "";
    std::cout << "Input: ";
    // Wait for input
    std::getline(std::cin, input);
    // Evaluate input
    input_recv(input);
    return 0;
}

感谢这个社区。开关/外壳控制现在对我有用。我也在尝试这里提到的其他控件。感谢所有帮助过的人...