C ++字符验证问题

时间:2015-10-22 09:58:33

标签: c++ validation

控制台应用程序中(Y / N)输入的验证有效但如果用户没有输入任何内容并只是按下“Enter”按钮,则光标将不会返回其原始的二维位置。 (它返回到原始位置下方的行)

我不知道为什么。这是代码:

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;
}

1 个答案:

答案 0 :(得分: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?