Solved

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

Posted on 1998-07-25
8
201 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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 use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

838 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