std::cin woes ---- C style macros to the rescue

  • Thread starter Generic Usenet Account
  • Start date
G

Generic Usenet Account

Sick and tired of the problems that cin was giving me in a menu-driven
CLI application, that accepts numerical inputs (I was getting into an
infinite loop when a non-numerical input was entered), I have gone
ahead and defined the following macro:


#define readStdin(x) while(true) \
{ \
cin >> x; \
if(!cin) \
{ \
cin.clear(); \
cin.ignore(MAX_LINE_LEN, '\n'); \
} \
else \
break; \
}

This macro has been working like a charm for me. Any other
suggestions are welcome. (Yes I know that I can read the line into a
buffer and read input from that buffer, but that's not what I want to
do).

Regards,
KP Bhat
 
E

E. Robert Tisdale

Generic said:
Sick and tired of the problems that cin was giving me in a menu-driven
CLI application, that accepts numerical inputs (I was getting into an
infinite loop when a non-numerical input was entered), I have gone
ahead and defined the following macro:


#define readStdin(x) while(true) \
{ \
cin >> x; \
if(!cin) \
{ \
cin.clear(); \
cin.ignore(MAX_LINE_LEN, '\n'); \
} \
else \
break; \
}

This macro has been working like a charm for me. Any other
suggestions are welcome. (Yes I know that I can read the line into a
buffer and read input from that buffer, but that's not what I want to
do).

So what is your question?

Take a deep breath and tell us what's wrong.
Post a [short] complete program that demonstrates the problem
then show us the error messages that you got from your compiler
and any diagnostic messages that you got when you tried to run it.
 
S

Simon Saunders

Sick and tired of the problems that cin was giving me in a menu-driven
CLI application, that accepts numerical inputs (I was getting into an
infinite loop when a non-numerical input was entered), I have gone
ahead and defined the following macro:


#define readStdin(x) while(true) \
{ \
cin >> x; \
if(!cin) \
{ \
cin.clear(); \
cin.ignore(MAX_LINE_LEN, '\n'); \
} \
else \
break; \
}

This macro has been working like a charm for me. Any other
suggestions are welcome. (Yes I know that I can read the line into a
buffer and read input from that buffer, but that's not what I want to
do).

I prefer to avoid macros where possible. I'd write it as a function
template:

template <typename T>
void readStdin(T& x)
{
....
}

Perhaps there ought to be a return value indicating success/failure.
 
R

Rob Williscroft

E. Robert Tisdale wrote in
So what is your question?

It's right there above your question: "...Any other suggestions are
welcome. ... "

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top