Solved

What's wrong with my do-while/if statement??

Posted on 1998-07-25
8
203 Views
Last Modified: 2010-04-02
Hi!

I'm having a little problem with my program (see below). It does what it's supposed to do, so far.  However, there is one big problem I'm hoping someone can make small for me.

Most of the way down the code, you will see the do-while loop.  Now, the program works okay as long as a number is entered.  is used to go into an infinite loop whenever a character is entered. I added an else statement, suppose dto display a message is anything other than specified int he if statement is entered.  All this did was make the program crash when a single letter is entered, and the infinite loop occurs ONLY if a letter is entered inadvertantly (or on purpose) along with a number (examples: t crashes the program, where 3e starts the infinite loop).

Can someone help me with this little problem? It really is driving me NUTS! I'm not even sure if it's the do-while loop causing this.  Could it only be the if statement?

The code (in it's entirity):

#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <bool.h>
#include <windows.h>

struct digit
{    int Value;
      digit* Next;
};

typedef digit* number;
number Head;
number Curr;
number Prev;
number Nu;

void Insert(int data)
// Insert() accepts input from user and places data in a node on the
// linked list
{
      Nu = new digit;
      Nu->Value = data;
      Nu->Next = Head;
      Head = Nu;

}

void Retrieve()
// Retrieve() will display all integer data in linked list
{
      for(Curr = Head; Curr != NULL; Curr=Curr->Next)
            {
                  cout <<Curr->Value<<",";
            }

}

digit* Increment(number N)
{
      if(N != NULL)
      {
            N = Head;
            N->Value += 1;
            //Head = Head->Next;
      }
      return N;
}
main()
{
      int Num;
      char reply;
      while(1)
      {
      cout <<"I) Insert Data\n"
              <<"R) Retrieve Data\n"
              <<"N} Increment Data\n"
              <<"X) Exit\n\n "<<flush;
      cin >> reply;

      reply = toupper(reply);

      switch(reply)
      {
            case 'I':
            cout << "Enter the number '10' to terminate input!"<<endl;

            do
            {

            clrscr();

            cout << "Enter Data:"<<flush;
            cin >> Num;
            if((isalpha(Num)== false)&& (Num >= 0) && (Num <= 9))
                  {
                  Insert(Num);
                  }
            else
                  {
                  cout << "Error! Enter a number int he range of 0 and 9!\n" << endl;
                  }

            }while(Num != 10);

            break;

            case 'R':
            Retrieve();
            getch();
            clrscr();
            break;

            case 'N':
            Increment(Head);
            getch();
            clrscr();
            break;

            case 'X':
            PostQuitMessage(0);
            exit(0);
            break;
      }

  }
}

Thanks in advance!

Mike Wonch
0
Comment
Question by:mwonch
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 

Author Comment

by:mwonch
ID: 1168665
Adjusted points to 75
0
 
LVL 7

Expert Comment

by:psdavis
ID: 1168666
if((isalpha(Num)== false)&& (Num >= 0) && (Num <= 9))

How about

if( isdigit( Num ))

Phillip  (still thinkin...)
0
 
LVL 6

Accepted Solution

by:
snoegler earned 70 total points
ID: 1168667
1.Your code is:
                             cin>>Num;

Where "Num" is defined as an integer: Now the cin stream tries to read an integer from the
standard input, which fails if a character( for example 'x') is entered. You won't get the ascii
code of it(like you seem to assume), but the value 0 (zero), because it can't be converted to
a number. So your check with isalpha(Num) will ever be false ...

2. Now the problem is that 'cin >> Num' stops reading from the stream when reading a
non-digit character which is the case in your error condition. That means, each cin >> Num
stops before reading anything from the stream(or it just produces a runtime error, depending
on your compiler and debug/release model).  So the input buffer stays filled - each attempt to
read an integer fails, no character is taken from the stream, and so on ...(and because the
input buffer IS filled, cin won't fetch another input and just passes by without waiting for a
keypress)

I would use the getch() function instead ... (i know i will get now a comment like 'bad karma' or
something like that, but it IS a C AND C++ function ...)
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 7

Expert Comment

by:psdavis
ID: 1168668
Just say that snoegler found you a working answer.  Since I already had it done (and I've never done cin and cout, I made this a learning project), here's my answer...

Instead of a simple

   cin >> num;

How about getting character data, after all, all data is valid!

   char line[ 100 ];
   cin.getline( line, 100, '\n' );

   cin.getline( line, 100, '\n' );
// cin >> reply;
     
   line[ 0 ] = toupper( line[ 0 ] );
     
   switch( line[ 0 ] )
   {
   case 'I':
      cout << "Enter the number '10' to terminate input!"<<endl;
         
      do
      {
         clrscr();
         cout << "Enter Data:"<<flush;

         cin.getline( line, 100, '\n' );

         if( isdigit( line[ 0 ] ))
         {
            Insert( line[ 0 ] );
         }
         else
         {
            cout << "Error! Enter a number int he range of 0 and 9!\n" << endl;
         }

      }while( atoi( line ) != 10);
 
Talk about a bad 'karma' answer!!

Phillip

0
 
LVL 6

Expert Comment

by:snoegler
ID: 1168669
This should work but there is one thing wrong, i think:
If the user enters '10' to stop the input loop, then 'isdigit(line[0])' returns TRUE and so another number is inserted ('1').
I don't like these 'cin' and 'cout' things ... ;)
0
 
LVL 7

Expert Comment

by:psdavis
ID: 1168670
Good point, I can't stand those cin and cout(s) either!! I'm a MFC man myself.  (No questions to answer over there, I'm slummin') You are right about the isdigit, it should be more like

Num = atoi( line );

but once I saw that you already provided a good answer, I kinda lost the heart to finish everything!!

Phillip

0
 
LVL 6

Expert Comment

by:snoegler
ID: 1168671
I made a mistake myself ;)
With just a simple getch() you will never get more than one char at a time ...
So entering '10' is not possible ...
This idea with cin.getline and atoi() that you mentioned would be better.
So now i lost the heart no finish everything <G>
0
 
LVL 7

Expert Comment

by:psdavis
ID: 1168672
Don't lose heart now!  You got the points!!!

Phillip

0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question