Re: Avoiding Input Failure in C++
Marcel M?ller wrote:
Hi,
orgthingy wrote:
so how can I avoid input failure? ..to those who are confused by my
question, i mean how to avoid getting double-input into an int variable?
and so on
In good old C you can write
size_t n = -1;
int i;
sscanf(input, "%i%n", &i, &n);
if (n == strlen(input))
// It was an int and nothing but an int.
else
// Invalid input
This is reliable, at least for numeric types.
Something similar can be done using stringstreams:
#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>
struct read_error : public std::runtime_error {
read_error ( std::string const & what_arg )
: std::runtime_error( what_arg )
{}
};
template < typename T >
T read ( std::string const & word ) {
std::istringstream stream ( word );
T result;
if ( stream >> result ) {
char dummy;
if ( stream >> dummy ) {
throw ( read_error( "leftover characters" ) );
}
return ( result );
} else {
throw ( read_error( "conversion failed" ) );
}
}
int main ( void ) {
std::string word;
while ( std::cin >> word ) {
try {
int i = read<int>( word );
std::cout << "int = " << i << std::endl;
}
catch ( read_error const & e ) {
std::cout << e.what() << std::endl;
}
}
}
Best
Kai-Uwe Bux