Re: Avoiding Input Failure in C++
On Dec 26, 8:30 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
Marcel M=FCller wrote:
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 ) {
Just curious, but what's wrong with just:
if ( stream.get() != EOF ) ...
Saves the extra variable, and IMHO, it better says what you are
trying to do.
It also has slightly different semantics; your version will
skip trailing spaces before trying to read the character; mine
won't. If skipping trailing spaces is desired (often a good
idea), then throw in a ">> std::ws" somewhere before the get.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34