473,385 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Verifying valid input in a loop

JR
Hey all,

I have read part seven of the FAQ and searched for an answer but can
not seem to find one.

I am trying to do the all too common verify the data type with CIN.
The code from the FAQ looks like this:

#include <iostream>

int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // GOOD FORM
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
This works well except that I do not want to exit the loop unless a
valid input is entered. So if I enter an 'a' I want to stay in the
loop to allow for another chance at input not exit the loop. Can
someone please provide a modified version of this code that will allow
this?
Thanks,

James
Jul 22 '05 #1
7 7260

"JR" <JR*****@email.com> wrote in message
news:8b**************************@posting.google.c om...
Hey all,

I have read part seven of the FAQ and searched for an answer but can
not seem to find one.

I am trying to do the all too common verify the data type with CIN.
The code from the FAQ looks like this:

#include <iostream>

int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // GOOD FORM
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
This works well except that I do not want to exit the loop unless a
valid input is entered. So if I enter an 'a' I want to stay in the
loop to allow for another chance at input not exit the loop. Can
someone please provide a modified version of this code that will allow
this?


It's difficult to validate input, it gets very fiddly. C++ cannot provide a
standard solution because what is valid input for one program is not valid
for another. And since you don't say what is valid input for your program
its impossible to give a detailed answer. I would guess that only positive
integers and -1 are valid for you.

However the general approach is simple enough. Read the input as a string,
check to see if the string is a valid number (whatever that means for your
program) and only then convert the string to an integer.

John
Jul 22 '05 #2
JR writes:
I am trying to do the all too common verify the data type with CIN.
The code from the FAQ looks like this:

#include <iostream>

int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // GOOD FORM
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
This works well except that I do not want to exit the loop unless a
valid input is entered. So if I enter an 'a' I want to stay in the
loop to allow for another chance at input not exit the loop. Can
someone please provide a modified version of this code that will allow
this?


The overloaded >> specifies conversion. There is no back door way to get
the faulty input (for example, a letter), the stream goes into a fail state
if it gets bad input. So base your solution on getline() and do the
conversion "manually". Also, see ios::fail() and ios::clear(). The
simplest conversion would probably be strtol() in cstdlib. Using the stuff
in the iostreams package would be more elegant, but IMO harder.

You would have to give up the ability to display the faulty input to the
user if you wanted to persist in using cin.
Jul 22 '05 #3
In article <8b**************************@posting.google.com >,
JR <JR*****@email.com> wrote:

#include <iostream>

int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // GOOD FORM
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
This works well except that I do not want to exit the loop unless a
valid input is entered. So if I enter an 'a' I want to stay in the
loop to allow for another chance at input not exit the loop. Can
someone please provide a modified version of this code that will allow
this?


First, let's just do the error checking for a single input, and not worry
about the "-1 to quit" yet:

int i;
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear(); // reset stream status flags
cin.ignore(1000,'\n'); // skip past next newline (ENTER), or 1000
// chars, whichever comes first
cout << "Hey dummy, I said enter an integer! Try again: ";
}

If you want to input repeatedly until the user enters -1, wrap this in
another loop that tests for end of data:

int i = 0;
while (i != -1)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
if (i != -1)
{
// process i normally
}
}

Or you can make the real processing-code a bit cleaner by writing a
function to do the input and error-checking:

bool GetNumber (int& num)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> num))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
return (num != -1); // returns true if not at end of input yet
}

// the real processing-code

int i;
while (GetNumber(i))
{
// process i normally
}

--
Jon Bell <jt*******@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #4
JR
jt*******@presby.edu (Jon Bell) wrote in message news:<ch**********@jtbell.presby.edu>...
<snip>>

First, let's just do the error checking for a single input, and not
worry
about the "-1 to quit" yet:

int i;
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear(); // reset stream status flags
cin.ignore(1000,'\n'); // skip past next newline (ENTER), or 1000
// chars, whichever comes first
cout << "Hey dummy, I said enter an integer! Try again: ";
}

If you want to input repeatedly until the user enters -1, wrap this in
another loop that tests for end of data:

int i = 0;
while (i != -1)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
if (i != -1)
{
// process i normally
}
}

Or you can make the real processing-code a bit cleaner by writing a
function to do the input and error-checking:

bool GetNumber (int& num)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> num))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
return (num != -1); // returns true if not at end of input yet
}

// the real processing-code

int i;
while (GetNumber(i))
{
// process i normally
}


Thanks All,

Jon I really like your solution. I came across is a couple hours
after I posted in this post .

http://groups.google.com/groups?hl=e...ng.c.moderated

This is essentially what I did and it is similar to the solution you
provided. It seems very elegant and easy to use. The ironic thing is
he posted that code to help him solve another problem. So his problem
was my solution. :)

Thank you again.
Jul 22 '05 #5

"JR" <JR*****@email.com> wrote in message
news:8b**************************@posting.google.c om...
jt*******@presby.edu (Jon Bell) wrote in message
news:<ch**********@jtbell.presby.edu>...
<snip>>

First, let's just do the error checking for a single input, and not
worry
about the "-1 to quit" yet:

int i;
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear(); // reset stream status flags
cin.ignore(1000,'\n'); // skip past next newline (ENTER), or
1000
// chars, whichever comes first
cout << "Hey dummy, I said enter an integer! Try again: ";
}

If you want to input repeatedly until the user enters -1, wrap this in
another loop that tests for end of data:

int i = 0;
while (i != -1)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
if (i != -1)
{
// process i normally
}
}

Or you can make the real processing-code a bit cleaner by writing a
function to do the input and error-checking:

bool GetNumber (int& num)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> num))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
return (num != -1); // returns true if not at end of input yet
}

// the real processing-code

int i;
while (GetNumber(i))
{
// process i normally
}


Thanks All,

Jon I really like your solution. I came across is a couple hours
after I posted in this post .


It has a weakness. Most people would consider 123abc to be erroneous input.
But the code above will read this as the integer 123, then loop and read abc
(which obviously it would consider an error).

If you want to avoid this problem, then you must read as a string and then
convert to an integer.

john

Jul 22 '05 #6

"JR" <JR*****@email.com> schrieb im Newsbeitrag
news:8b**************************@posting.google.c om...
Hey all,

I have read part seven of the FAQ and searched for an answer but can
not seem to find one.

I am trying to do the all too common verify the data type with CIN.
The code from the FAQ looks like this:

#include <iostream>

int main()
{
std::cout << "Enter a number, or -1 to quit: ";
int i = 0;
while (std::cin >> i) { // GOOD FORM
if (i == -1) break;
std::cout << "You entered " << i << '\n';
}
}
This works well except that I do not want to exit the loop unless a
valid input is entered. So if I enter an 'a' I want to stay in the
loop to allow for another chance at input not exit the loop. Can
someone please provide a modified version of this code that will allow
this?
Thanks,

James


I would do it like this:

#include <iostream>

using namespace std;

//clears an error in an input stream object like cin
//and makes it usable again by clearing the associated stream buffer
int ClearError(istream& isIn) // Clears istream object
{
streambuf* sbpThis;
char szTempBuf[20];
int nCount, nRet = isIn.rdstate();

if (nRet) // Any errors?
{
isIn.clear(); // Clear error flags
sbpThis = isIn.rdbuf(); // Get streambuf pointer
nCount = sbpThis->in_avail(); // Number of characters in buffer

while (nCount) // Extract them to szTempBuf
{
if (nCount > 20)
{
sbpThis->sgetn(szTempBuf, 20);
nCount -= 20;
}
else
{
sbpThis->sgetn(szTempBuf, nCount);
nCount = 0;
}
}
}

return nRet;
}
int main()
{
int pri = 0;
cout << "Enter a number: " << endl;
do
{
ClearError(cin);
cin >> pri;
} while (!cin);
return 0;
}
Jul 22 '05 #7
JR
"John Harrison" <jo*************@hotmail.com> wrote in message news:<2q************@uni-berlin.de>...
"JR" <JR*****@email.com> wrote in message
news:8b**************************@posting.google.c om...
jt*******@presby.edu (Jon Bell) wrote in message
news:<ch**********@jtbell.presby.edu>...
<snip>>

First, let's just do the error checking for a single input, and not
worry
about the "-1 to quit" yet:

int i;
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear(); // reset stream status flags
cin.ignore(1000,'\n'); // skip past next newline (ENTER), or
1000
// chars, whichever comes first
cout << "Hey dummy, I said enter an integer! Try again: ";
}

If you want to input repeatedly until the user enters -1, wrap this in
another loop that tests for end of data:

int i = 0;
while (i != -1)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> i))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
if (i != -1)
{
// process i normally
}
}

Or you can make the real processing-code a bit cleaner by writing a
function to do the input and error-checking:

bool GetNumber (int& num)
{
cout << "Please enter an integer, and press ENTER: ";
while (! (cin >> num))
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Hey dummy, I said enter an integer! Try again: ";
}
return (num != -1); // returns true if not at end of input yet
}

// the real processing-code

int i;
while (GetNumber(i))
{
// process i normally
}


Thanks All,

Jon I really like your solution. I came across is a couple hours
after I posted in this post .


It has a weakness. Most people would consider 123abc to be erroneous input.
But the code above will read this as the integer 123, then loop and read abc
(which obviously it would consider an error).

If you want to avoid this problem, then you must read as a string and then
convert to an integer.

john

That is a good point. It also has the weakness of if 100,000 is
entered then only 100 is taken. It does seem that overall the input
as a string makes the most sense.

James
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Chris Sharman | last post by:
I'm doing a rough validation of an email address client-side (using js), but it's not enough - our customer service people are apparently incapable of typing in an email address without error - we...
1
by: jel | last post by:
I ran what was submitted in several forums, but it's not exactly what i'm looking for. I'm dy'n over here. Ah, the frustrations of an amateur programmer. I included the code below in c++. which...
10
by: Doug O'Leary | last post by:
Hey, all. I have a perl script which generates the html listed below. I cleaned it up a bit since the perl CGI module creates some really ugly html code. I've looked at this thing 8 ways to...
5
by: DS | last post by:
How does one set-up a macro to do the following. When you enter an Employee Number in a log-in box Access checks the Employee Table to see if thats a valid Employee number. if it is the Macro...
6
by: John | last post by:
Hi I have several web forms that require users verification by entering a code before they are allowed in. I have created a separate web form for entering and verifying user code. How do I...
7
by: Hulo | last post by:
In a C program I am required to enter three numbers (integers) e.g. 256 7 5 on execution of the program. C:\> 256 7 5 There should be spaces between the three numbers and on pressing "enter",...
2
by: Sethos | last post by:
I am sure that this has been covered, hashed, and rehashed, but a search on the group did not produce the answer, so forgive me if this seems like a "newbie" type question... Besically, I have a...
4
by: Mike | last post by:
Hi all, In my recent ASP.NET 2.0 appl, I need to verify that the supplied email address is valid or not. So, here's my situation: - In my <profilearea, I created <isVerifiedproperty. - Suppose a...
1
by: foothills bhc | last post by:
I have a problem with verifying content of controls on a form before closing the form or moving to the next form "record" (i.e., when moving to the next row of my form's record source). HERE'S THE...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.