2011-04-09 25 views
1

我需要使用C++的更多幫助, 可以說我不知道​​自己多大了,我想回到按下ESC的「function2」。 我想要的東西,當我按下ESC(不要緊的時候)它忽略了「cin」並轉到「function2」。 (我知道我並不需要所有庫)忽略「cin」並使用「kbhit」轉到另一個函數

#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; 
} 
+1

borland/watcom打來電話,他們希望自己的kbhit()回來! – stefan 2011-04-09 03:49:34

+0

@stefan:不是Borland特有的,['kbhit'(和'_kbhit')由Microsoft C運行庫提供](http://msdn.microsoft.com/zh-cn/library/ms235390.aspx) – 2011-04-09 04:03:35

回答

1

conio.h是一個過時和不標準C庫。爲了從輸入中得到一個字符,你必須通過cin(例如cin.get()),或者使用與系統相關的功能,在這種情況下,您需要查看您的編譯器爲您的平臺提供的庫。如果可用,請嘗試getch()(另一個非便攜式功能)。

At this site你可以找到幾個關於如何實現你所需要的例子。

0

conio.h不提供任何異步I/O信號的手段。 (更重要的是,conio.h甚至不是C或C++標準的一部分,我不建議在Mac或Linux上使用它。)您需要實現自己的輸入系統(基本上重寫istream::operator >>或可笑的危險gets)使用getch分支特殊鍵。我建議重新考慮你的輸入設計,因爲即使產生了第二個線程以觀察GetKeyState(我假設你在Windows上)並且屏住呼吸也不會輕易中斷另一個線程上的getline

0

除了conio.h之類的問題之外,你的原始代碼的另一個問題是你正在測試浮點數,例如

if (c==27)
鑑於你的輸入需要字符,你應該使用char (或整數)類型(忽略可能的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; 
} 

當然,也有這種方法的問題 - 處理,你需要使用的功能函數GetKeyState,從WinAPI的範圍內進行適當的活動。