Solved

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

Posted on 1998-07-25
8
195 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
  • 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
 
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now