c++字符验证问题

C++ Character Validation issue

本文关键字:问题 验证 字符 c++      更新时间:2023-10-16

在控制台应用程序中验证(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;
}

技巧是这样的:当你按[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而不是一个字符——这将消除在您的场景中忽略的必要性。另外,请参见这个问题:清除cin输入:是cin。忽视不是一个好办法吗?