2015-10-22 39 views
3

驗證控制檯應用程序中的(Y/N)輸入有效,但如果用戶沒有輸入任何內容,只需按下「Enter」按鈕,則光標將不會返回到其原始的二維位置。 (它返回到原來的位置以下的線)C++字符驗證問題

我不知道爲什麼。這裏是代碼:

char again(int col, int row) 
{ 
char reply; 

do 
{ 
    gotoXY(col, row); 
    cin >> noskipws >> reply; 
    reply = toupper(reply); 

    if ((reply != 'Y' && reply != 'N')) 
    { 
     message("Must Enter Y or N ", 5, row + 3); 
     clearLine(col, row);    

    // cin.clear(); 
     cin.ignore(150, '\n'); 
    } 

    cin.setf(ios::skipws);  

} while (reply != 'Y' && reply != 'N'); 

return reply; 
} 

有什麼建議嗎?

這應該允許您編譯和看待這個問題:

#include "stdafx.h" 
#include <conio.h> 
#include <iostream> 
#include <Windows.h> 
#include <iomanip> 


using namespace std; 

VOID gotoXY(short x, short y); 
char again(int col, int row); 
void clearLine(int col, int row); 
void pressKey(int col, int row); 
void message(char message[], int col, int row); 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
char reply; 
do 
{ 
    gotoXY(5, 13); 
    cout << "Do you want to run the program again (Y/N):"; 
    reply = again(51, 13); 

    cin.ignore(150, '\n'); 

} while (reply == 'Y'); 

return 0; 
} 
VOID gotoXY(short x, short y) 
{ 
COORD c = { x, y }; 
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c); 
} 


void message(char message[], int col, int row) 
{ 
gotoXY(col, row); 
cout << message; 
pressKey(col, row + 2); 
clearLine(col, row); 
clearLine(col, row + 2); 
} 

void pressKey(int col, int row) 
{ 
gotoXY(col, row); 
cout << "Press any key to continue..."; 
_getch(); 
} 


void clearLine(int col, int row) 
{ 
//Used to clear prompts and user input 
gotoXY(col, row); 

for (int i = col; i <= 80; i++) 
{ 
    cout << " "; 
} 
} 

char again(int col, int row) 
{ 
char reply; 

do 
{ 
    gotoXY(col, row); 
    cin >> noskipws >> reply; 
    reply = toupper(reply); 

    if ((reply != 'Y' && reply != 'N')) 
    { 
     message("Must Enter Y or N ", 5, row + 3); 
     clearLine(col, row); 
     cin.setf(ios::skipws); 
     // cin.clear(); 
     cin.ignore(150, '\n'); 
    } 

    /*cin.setf(ios::skipws);*/ 

} while (reply != 'Y' && reply != 'N'); 

return reply; 
} 
+3

您需要提供更多上下文。 'message()'和'clearLine()'做了什麼?當你說光標沒有返回到它的當前位置時,你的意思是水平位置(例如到左邊距的特定偏移量)還是二維位置(例如屏幕左上角的水平和垂直偏移量)?最後,您的程序在哪個環境中運行 - 它是一個控制檯應用程序,您是否依賴於特定的設備特性(例如將光標移動到2D屏幕上的特定位置),這些特性在所有屏幕上都不可用? – Peter

+1

@SkottokS:如果你提供了最小但足夠完整的代碼來編譯代碼,那將是非常棒的。 – anurag86

+0

是gotoXY()一個預定義函數(可能是)?如果是這樣,請指定您的操作系統,編譯器以及如何運行您的應用程序(否則,請提供gotoXY()的源代碼)。大多數「現代」功能被稱爲gotoxy(),所以我有一種感覺,你使用的是過時的庫,它可能會在現代操作系統中產生奇怪的效果。 – Abstraction

回答

1

這是使用方法:當您按下[T],[Enter]鍵,兩個符號被添加到流: 'T',」 \ N」。首先閱讀std::cin >> reply,其次閱讀std::cin.ignore(150,'\n');

但是當你按[Enter]時,只有'\ n'被添加到流中。它被讀取爲回覆,並且當控制達到std::cin.ignore(150,'\n');時,沒有符號要從流中讀取;此時,輸入光標留在clearLine()離開它的位置,並且所有其他輸入直到'\ n'(或前150個符號)將被忽略。

簡單(雖然不是最好的)解決方案將檢查if (reply != '\n') cin.ignore(150, '\n');。更好的主意是不讀一個字符,但從一開始std::string - 這將消除在您的情況下忽略的必要性。另請參閱此問題:Clearing cin input: is cin.ignore not a good way?