473,386 Members | 1,795 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,386 software developers and data experts.

Validating input

I saw these two ways for validating input

First Way
--------------
#include <iostream>
#include <limits>

using namespace std;

int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');

if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}

Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {

int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}

Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?

Dec 9 '06 #1
5 2300

Kavya wrote:
I saw these two ways for validating input

First Way
--------------
#include <iostream>
#include <limits>

using namespace std;

int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');

if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}

Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {

int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}

Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?
How about:

#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <limits>
#include <typeinfo>
#include <stdexcept>

// may need a specialization to capture std::string
template < typename T >
void parseInput( std::vector< T >& r_vt ) {
std::cout << "Enter a series of " << typeid(T).name();
std::cout << " (any char to terminate)" << std::endl;
T t;
while ( std::cin >t ) {
if ( !std::cin.good() ) {
throw std::runtime_error( "reading input stream." );
}
r_vt.push_back( t );
}
std::cin.clear();
std::cin.ignore(std::numeric_limits< int >::max(), '\n');
}

// op<< for std::vector< T >
template< typename T >
std::ostream&
operator<<( std::ostream& os,
const std::vector< T >& r_vt )
{
std::copy( r_vt.begin(),
r_vt.end(),
std::ostream_iterator< T >( os, "\n" ) );
return os;
}

int main() {
try {
std::vector< int vn;
parseInput( vn );
std::cout << vn;

std::vector< double vd;
parseInput( vd );
std::cout << vd;

} catch ( std::exception & r_e ) {
std::cerr << "\nError: " << r_e.what();
std::cerr << std::endl;
}
}

/*
Enter a series of i (any char to terminate)
-1
0
1
a // <- terminated
-1
0
1
Enter a series of d (any char to terminate)
-11.1
0.009
3.14159
a // <- terminated
-11.1
0.009
3.14159
*/

Dec 9 '06 #2

Salt_Peter wrote:
Kavya wrote:
I saw these two ways for validating input

First Way
--------------
#include <iostream>
#include <limits>

using namespace std;

int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');

if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}

Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {

int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}

Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?

How about:

#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <limits>
#include <typeinfo>
#include <stdexcept>

// may need a specialization to capture std::string
template < typename T >
void parseInput( std::vector< T >& r_vt ) {
std::cout << "Enter a series of " << typeid(T).name();
std::cout << " (any char to terminate)" << std::endl;
T t;
while ( std::cin >t ) {
if ( !std::cin.good() ) {
throw std::runtime_error( "reading input stream." );
}
r_vt.push_back( t );
}
std::cin.clear();
std::cin.ignore(std::numeric_limits< int >::max(), '\n');
}

// op<< for std::vector< T >
template< typename T >
std::ostream&
operator<<( std::ostream& os,
const std::vector< T >& r_vt )
{
std::copy( r_vt.begin(),
r_vt.end(),
std::ostream_iterator< T >( os, "\n" ) );
return os;
}

int main() {
try {
std::vector< int vn;
parseInput( vn );
std::cout << vn;

std::vector< double vd;
parseInput( vd );
std::cout << vd;

} catch ( std::exception & r_e ) {
std::cerr << "\nError: " << r_e.what();
std::cerr << std::endl;
}
}

/*
Enter a series of i (any char to terminate)
-1
0
1
a // <- terminated
-1
0
1
Enter a series of d (any char to terminate)
-11.1
0.009
3.14159
a // <- terminated
-11.1
0.009
3.14159
*/
That didn't answer my question. Your solution is way beyond my reach.

Dec 9 '06 #3

Kavya wrote:
Salt_Peter wrote:
Kavya wrote:
I saw these two ways for validating input
>
First Way
--------------
#include <iostream>
#include <limits>
>
using namespace std;
>
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');
>
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
>
Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
>
int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}
>
Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?
How about:

#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <limits>
#include <typeinfo>
#include <stdexcept>

// may need a specialization to capture std::string
template < typename T >
void parseInput( std::vector< T >& r_vt ) {
std::cout << "Enter a series of " << typeid(T).name();
std::cout << " (any char to terminate)" << std::endl;
T t;
while ( std::cin >t ) {
if ( !std::cin.good() ) {
throw std::runtime_error( "reading input stream." );
}
r_vt.push_back( t );
}
std::cin.clear();
std::cin.ignore(std::numeric_limits< int >::max(), '\n');
}

// op<< for std::vector< T >
template< typename T >
std::ostream&
operator<<( std::ostream& os,
const std::vector< T >& r_vt )
{
std::copy( r_vt.begin(),
r_vt.end(),
std::ostream_iterator< T >( os, "\n" ) );
return os;
}

int main() {
try {
std::vector< int vn;
parseInput( vn );
std::cout << vn;

std::vector< double vd;
parseInput( vd );
std::cout << vd;

} catch ( std::exception & r_e ) {
std::cerr << "\nError: " << r_e.what();
std::cerr << std::endl;
}
}

/*
Enter a series of i (any char to terminate)
-1
0
1
a // <- terminated
-1
0
1
Enter a series of d (any char to terminate)
-11.1
0.009
3.14159
a // <- terminated
-11.1
0.009
3.14159
*/

That didn't answer my question. Your solution is way beyond my reach.
I don't see why you seem to think its beyond your reach, there isn't
anything misterious about it.
It also emphasizes that i like better your #2 solution except that i'ld
not combine a std::cin >extraction with a std::cin.good check
together in a conditional expression for a while loop.

If you prefer without exceptions, return with an error message. What
you do not want to do is have a while loop fail silently without some
kind of feedback.

....
while( std::cin >inum )
{
if( !std::cin.good() )
{
std::cerr << "error in standard input.\n";
return -1;
}
// do stuff
}
....

Besides, if you needed a while loop to process 2 conditionals, you'ld
do it like so:

while( !condition1 || condition2 )
{
// do stuff
}

which would mean that if either condition fails, the program exits the
while loop silently.
Not exactly what you want. And note that condition2 above is not even
processed should the first condition fail.

Dec 10 '06 #4


On Dec 10, 6:25 pm, "Salt_Peter" <pj_h...@yahoo.comwrote:
Kavya wrote:
Salt_Peter wrote:
Kavya wrote:
I saw these two ways for validating input
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}
Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?
How about:
#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <limits>
#include <typeinfo>
#include <stdexcept>
// may need a specialization to capture std::string
template < typename T >
void parseInput( std::vector< T >& r_vt ) {
std::cout << "Enter a series of " << typeid(T).name();
std::cout << " (any char to terminate)" << std::endl;
T t;
while ( std::cin >t ) {
if ( !std::cin.good() ) {
throw std::runtime_error( "reading input stream." );
}
r_vt.push_back( t );
}
std::cin.clear();
std::cin.ignore(std::numeric_limits< int >::max(), '\n');
}
// op<< for std::vector< T >
template< typename T >
std::ostream&
operator<<( std::ostream& os,
const std::vector< T >& r_vt )
{
std::copy( r_vt.begin(),
r_vt.end(),
std::ostream_iterator< T >( os, "\n" ) );
return os;
}
int main() {
try {
std::vector< int vn;
parseInput( vn );
std::cout << vn;
std::vector< double vd;
parseInput( vd );
std::cout << vd;
} catch ( std::exception & r_e ) {
std::cerr << "\nError: " << r_e.what();
std::cerr << std::endl;
}
}
/*
Enter a series of i (any char to terminate)
-1
0
1
a // <- terminated
-1
0
1
Enter a series of d (any char to terminate)
-11.1
0.009
3.14159
a // <- terminated
-11.1
0.009
3.14159
*/
That didn't answer my question. Your solution is way beyond my reach.I don't see why you seem to think its beyond your reach, there isn't
anything misterious about it.
It also emphasizes that i like better your #2 solution except that i'ld
not combine a std::cin >extraction with a std::cin.good check
together in a conditional expression for a while loop.

If you prefer without exceptions, return with an error message. What
you do not want to do is have a while loop fail silently without some
kind of feedback.

...
while( std::cin >inum )
{
if( !std::cin.good() )
{
std::cerr << "error in standard input.\n";
return -1;
}
// do stuff}...

Besides, if you needed a while loop to process 2 conditionals, you'ld
do it like so:

while( !condition1 || condition2 )
{
// do stuff

}which would mean that if either condition fails, the program exits the
while loop silently.
Not exactly what you want. And note that condition2 above is not even
processed should the first condition fail.
Thanks for the explanation. But I have 2 more questions regarding this.
1) Why have you used <limits>?
2) In case of this
if( !std::cin.good() )
{
std::cerr << "error in standard input.\n";
return -1;
}
I am not able to see the error message on screen if I enter wrong input.

Dec 10 '06 #5

Kavya wrote:
On Dec 10, 6:25 pm, "Salt_Peter" <pj_h...@yahoo.comwrote:
Kavya wrote:
Salt_Peter wrote:
Kavya wrote:
I saw these two ways for validating input
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >number;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int inum,count=0;
cout<<"Enter integers, <Returnafter each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}
Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?
How about:
#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <limits>
#include <typeinfo>
#include <stdexcept>
// may need a specialization to capture std::string
template < typename T >
void parseInput( std::vector< T >& r_vt ) {
std::cout << "Enter a series of " << typeid(T).name();
std::cout << " (any char to terminate)" << std::endl;
T t;
while ( std::cin >t ) {
if ( !std::cin.good() ) {
throw std::runtime_error( "reading input stream." );
}
r_vt.push_back( t );
}
std::cin.clear();
std::cin.ignore(std::numeric_limits< int >::max(), '\n');
}
// op<< for std::vector< T >
template< typename T >
std::ostream&
operator<<( std::ostream& os,
const std::vector< T >& r_vt )
{
std::copy( r_vt.begin(),
r_vt.end(),
std::ostream_iterator< T >( os, "\n" ) );
return os;
}
int main() {
try {
std::vector< int vn;
parseInput( vn );
std::cout << vn;
std::vector< double vd;
parseInput( vd );
std::cout << vd;
} catch ( std::exception & r_e ) {
std::cerr << "\nError: " << r_e.what();
std::cerr << std::endl;
}
}
/*
Enter a series of i (any char to terminate)
-1
0
1
a // <- terminated
-1
0
1
Enter a series of d (any char to terminate)
-11.1
0.009
3.14159
a // <- terminated
-11.1
0.009
3.14159
*/
That didn't answer my question. Your solution is way beyond my reach.I don't see why you seem to think its beyond your reach, there isn't
anything misterious about it.
It also emphasizes that i like better your #2 solution except that i'ld
not combine a std::cin >extraction with a std::cin.good check
together in a conditional expression for a while loop.

If you prefer without exceptions, return with an error message. What
you do not want to do is have a while loop fail silently without some
kind of feedback.

...
while( std::cin >inum )
{
if( !std::cin.good() )
{
std::cerr << "error in standard input.\n";
return -1;
}
// do stuff}...

Besides, if you needed a while loop to process 2 conditionals, you'ld
do it like so:

while( !condition1 || condition2 )
{
// do stuff

}which would mean that if either condition fails, the program exits the
while loop silently.
Not exactly what you want. And note that condition2 above is not even
processed should the first condition fail.

Thanks for the explanation. But I have 2 more questions regarding this.
1) Why have you used <limits>?
<limitsis for the std::numeric_limits<class which helps clean up
any residual values in std::cin before the next loop ( like the newline
entered by the user). Some implementations include <limits>
automatically from iostream and other includes. I don't know nor care,
since i use it, i include it.
If you comment out that line in the aforementioned program, you'll see
what i mean.
Note:
[15.6] Why is my program ignoring my input request after the first
iteration?
http://www.parashift.com/c++-faq-lit....html#faq-15.4
2) In case of this
if( !std::cin.good() )
{
std::cerr << "error in standard input.\n";
return -1;
}
I am not able to see the error message on screen if I enter wrong input.
good() returns an input stream flag, if you enter a char for example,
std::cin will not extract that char to an integer variable. That
does_not_constitute_an_error in the input stream itself. That
non-integer value stays in the std::cin input stream waiting to be
collected or extracted . The good() flag checks whether the std::cin
input stream itself has been compromised, which is a different
situation altogether.
Consult the following for an overview of the flags available:
http://www.cplusplus.com/ref/iostream/ios/good.html
i/o errors are very rare, but if you are writing a program that is
accidentally corrupting something like std::cin, you definitely want to
know, therefore the error check.

To answer your question, you know when a non-integer was entered since
that stops the while loop. Your thinking that the process is more
complicated than it is - its actually quite basic.
If you want to see a char that stopped the while-int loop, all you'ld
need to do is collect it...

int inum;
while( std::cin >inum ) // keep reading integers until no ints
available
{
...
}
char c;
while( std::cin >c ) // collect residual char values
{
std::cout << "non-int captured! -" << c << std::endl;
}

For the moment, focus on the fact that a user presses enter to input
his integer. The integer is then extracted to the variable which leaves
that enter in the std::cin stream. What enter actually is depends on
the platform.

Dec 10 '06 #6

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

Similar topics

5
by: The Plankmeister | last post by:
Hi... What's the best method of validating input characters? I would like to prevent users submitting exotic characters (such as those acquired on Windows Systems by pressing ALT+) and thought...
3
by: Mark | last post by:
Hi, Im trying to validate a form, all the validating works apart from one field. This particular field must consist of the first 2 characters as letters, & the following 5 as numbers. And if it...
6
by: mike | last post by:
Hello, After trying to validate this page for a couple of days now I was wondering if someone might be able to help me out. Below is a list of snippets where I am having the errors. 1. Line 334,...
2
by: bildad | last post by:
The following 'book example' of validating input seems to be incomplete. Since it is a beginner's book it may be intentional for simplicity. But I would like to know how to make this program work...
0
by: Bradley Bossard via DotNetMonster.com | last post by:
I am having an issue with the .NET framework (or C#) and validating events. I have implemented several validating event handlers for textboxes on a form. When I run the app, the form works...
9
by: chuck | last post by:
I need some help with validating user input. I am writing a C computer program for an intro to C course. Here is the situation. I am creating an application that will do currency conversions. ...
6
by: J Huntley Palmer | last post by:
What is the most efficient way to validate an input to conform to your needs? I need to make sure an input is a contiguous string with only printable characters (english alphabet+numbers only)...
6
by: Richard | last post by:
I'm validating a date and time string which must be EXACTLY of the format yy-mm-dd hh:mm:ss and extracting the six numeric values using sscanf. I'm using the format string "%2u-%2u-%2u...
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: 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: 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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.