如何使用两个字符来控制 C++ 程序的流程
How to use two characters to control the flow of a c++ program
如何使用两个字符(A 和 B(来控制当用户输入其中任何一个字符时执行代码的哪一部分..?Forexaple当用户输入A时,转到某种交易类型并要求用户输入该交易的信息。如果为 B,则执行其他一些牵引类型,将要求用户输入此类事务的信息。我刚开始学习编程(C++(请..
谢谢
C++作为一种
命令式编程语言,提供了几个控制语句,如if/else,while,switch或for来控制程序的流程。 它们在您目前正在阅读的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++有很多方法可以实现选择结构。
- 如果其他(基本上每种编程语言都有(
if (a)
{
//do something
}
else
{
//do something else
}
- 开关控制
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
}
- 标签和转到关键字
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;
}
- 函数调用
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;
}
感谢这个社区。开关/外壳控制现在对我有用。我也在尝试这里提到的其他控件。感谢所有帮助过的人...
相关文章:
- 控制允许动态运行c++的并发操作数
- 从控制台中删除最后打印的元素
- 是否可以使用if constexpr删除控制流语句
- 无法在windows控制台中为C++程序提供必要的输入
- 控制到达非空函数clang(-Wreturn-type)的末尾
- 查找 GCD:并非所有控制路径都返回值
- 通过 API 控制 DJI 相机
- 禁止在控制台上记录谷神星
- 是否可以使用一个类来控制 C++ 中另一个类的对象?(阿杜伊诺)
- 如何删除列出的"QGraphicsPathItem"对象以控制进程内存使用情况?
- 我在 C++ 代码中遇到错误警告:控制到达非空函数 [-Wreturn 类型] 的末尾
- C++ Python 模块在 Blender 中崩溃,但在 Python 控制台中不会崩溃
- wx通用目录控制错误"wxTheFileIconsTable was nullptr"
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- Cython通过浮点数的最快方式,用于高频控制回路
- 用户控制从 c++ 到 java 脚本的 Webassembly 访问调用
- C ++,如何从控制台中输入的字符串中删除字母?
- 如何从单独的线程控制 SFML 窗口?
- 如何防止 Windows 控制台上的回车键自动滚动
- 我们能否在stm32f中使用硬件定时器控制两个独立的进程