Reputation: 41
This validation of a (Y/N) input in a console application works but if the user inputs nothing and simply presses the "Enter" button then the cursor will not return to its original two dimensional position. (it returns to the line below its original position)
I have no idea why. Here's the code:
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;
}
Any suggestions?
This should allow you to compile and view the issue:
#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;
}
Upvotes: 3
Views: 113
Reputation: 1572
Here is the trick: when you press [T],[Enter], two symbols are added to stream: 't','\n'. First is read on std::cin >> reply
, second is read on std::cin.ignore(150,'\n');
.
But when you press just [Enter], only '\n' is added to stream. It is read to reply, and when control reaches std::cin.ignore(150,'\n');
, there are no symbols to read from the stream; at the moment, input cursor is left where clearLine()
left it and all further input until '\n' (or first 150 symbols) will be ignored.
Simple (though not the best) solution would be to check if (reply != '\n') cin.ignore(150, '\n');
. Better idea is to read not a character, but std::string
from the start - this will remove necessity for ignore in your scenario. Also, see this question: Clearing cin input: is cin.ignore not a good way?
Upvotes: 1