c++字符验证问题
C++ Character Validation issue
在控制台应用程序中验证(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。忽视不是一个好办法吗?
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- C++卡验证问题
- 在C++中验证for循环的问题
- 使用OpenSSL的SHA 512 HMAC消息身份验证的问题
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 库库尔身份验证问题
- 刽子手游戏的验证问题
- 程序不输出正确的标准偏差.另外,验证问题
- C++信用卡验证问题
- C++数据验证问题
- 验证我的超类或基类是宏或模板声称的那个类时出现问题
- if字符串验证循环出现问题
- c++字符验证问题
- Visual在c++中验证电子邮件有问题
- 验证二叉树的小问题
- C++SDL代码::块:在头文件中声明指向全局可验证性的指针,同时避免多个包含问题
- 一遍又一遍地验证文件时遇到问题