Error when entering wrong data type in do-while loop

J

Jeff

Hello

I need help with a problem

I have homework for a larger program than shown below but the code below
effectively shows the problem whem compiled and executed.

Basically, I want to be able keep the loop going even if a character
(alphabet) is entered when it should be a number i.e. the wrong data type is
entered by mistake.

The concept is 'that the loop should work under all conditions'.

At the moment if a character is entered, the result is that the screen
constantly scrolls and is not readable.


Ideally I would like to insert into the program a line to the effect

{
'if (n != int)
cout << "that is not a valid option. Please try again"
}

However, for those of you who know c++ better than me, you will know that
this cannot be entered

Is there any way of entering this logical statement





Below is a part of the code, when compiled and executed will demonstrate the
problem


#include <iostream.h>

int main()
{
unsigned long n;
do
{
cout<< " Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n" ;


}
while (n != 0);

return 0;
}
 
K

Karsten Baumgarten

Jeff said:
Hello

I need help with a problem

I have homework for a larger program than shown below but the code below
effectively shows the problem whem compiled and executed.

Basically, I want to be able keep the loop going even if a character
(alphabet) is entered when it should be a number i.e. the wrong data type is
entered by mistake.

The concept is 'that the loop should work under all conditions'.

At the moment if a character is entered, the result is that the screen
constantly scrolls and is not readable.


Ideally I would like to insert into the program a line to the effect

{
'if (n != int)
cout << "that is not a valid option. Please try again"
}

However, for those of you who know c++ better than me, you will know that
this cannot be entered

Is there any way of entering this logical statement





Below is a part of the code, when compiled and executed will demonstrate the
problem


#include <iostream.h>

int main()
{
unsigned long n;
do
{
cout<< " Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n" ;


}
while (n != 0);

return 0;
}

Add something like:

if (!isaplha(n) {
cout << "You were supposed to enter a number" << endl;
}
 
K

Karsten Baumgarten

Karsten said:
if (!isaplha(n) {
cout << "You were supposed to enter a number" << endl;
}

Sorry for the typo! The function is called isalpha().
 

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,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top