忽略"cin"并使用"kbhit"转到另一个函数

Ignoring "cin" and using "kbhit" to go to another function

本文关键字:函数 kbhit 另一个 cin 忽略      更新时间:2023-10-16

我需要更多的帮助使用c++,让我们假设我不知道我的年龄,我想回到"function2"按ESC。我想要的东西,当我按ESC(不重要的时候),它忽略了"cin",去"function2"。(我知道我不需要所有的库)

#include <iostream>
#include <math.h>
#include <windows.h>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
# include <conio.h>
using namespace std;

int function2();
float a, c;
int main(){
do {
    while (kbhit()) 
    {c = getch();}
    if (c==27)
    {function2();}
    cout << "How old are you?t" << c << endl;
    cin>>a;

    } while(c != 27);}

int function2(){
    cout<< "!!!END!!!n";
    return 0;
}

conio.h是一个已弃用的非标准C库。为了从输入中获得一个字符,您必须通过cin(例如cin.get()),或者使用与系统相关的功能,在这种情况下,您需要查看编译器为您的平台提供的库。如果可用,请尝试getch()(另一个不可移植的功能)。

在这个站点上,您可以找到一些关于如何实现所需内容的示例。

conio.h不提供任何异步I/O信令方式。(更重要的是,conio.h甚至不是C或c++标准的一部分。我不建议尝试在Mac或Linux上使用它。)您需要实现自己的输入系统(基本上是重写istream::operator >>或非常危险的gets),以便使用getch在特殊键上进行分支。我建议重新考虑你的输入设计,因为即使生成第二个线程来观看GetKeyState(我假设你在Windows上)屏住呼吸,也不会使中断另一个线程上的getline变得容易。

除了前面提到的conio.h之类的问题之外,原始代码的另一个问题是,您正在针对整数(例如

if (c==27)
)测试浮点数考虑到您的输入需要字符,您应该使用字符(或整数)类型(忽略可能的UTF-16键盘代码,考虑到您在Windows上,这是可能的)。

对于平台无关的代码,您可能希望这样做:

#include <iostream>
int function2();
int c;
int main(){
  do {
    cin >> c;
    if (c == 27) {
      function2();
    }
    cout << "How old are you?" << endl;
  } while (c != 27);
  return 0;
}
int function2() {
  cout << "!!!END!!!" << endl;
  return 0;
}

当然,这种方法有问题——为了正确处理事件,你需要在WinAPI中使用GetKeyState函数。