Solved

Easy questions - nested looping and default??

Posted on 1998-07-18
8
166 Views
Last Modified: 2010-04-10
Hi, all!

The following code is already done for my homework and needs nothing more to meet the requirements.  However, I want to do a couple of more things with it to make it look better.  If anyone can direct me inthis, I'd really be grateful.

First, what this program does is take a digit entry and output whether the digit was 1, 4, or 9 and 3, 5, or 6 (seperate counts).  If the entry (digits from 0 to 9, by the way) was neither of the six cases, then the counter ignores it and gives the current count and the number of digits processed so far.  In this program, 20 digits are to be processed. So far, only the initial statement to start the user off is output.  After the first number is entered, then only a blank space comes up for the next entry.  SO, I'd like to add the word "AGAIN: " and have it loop each time a new digit is processed until the final one is counted (number 20, in this case). Maybe it's th elate hours I'm keeping these days, but I just can;t get it to work.  Can someone help me with this?

Second, I want to add a default statement to the switch in the for of a message box error message.  Now, I want the error message to come up any time anything other than 0 - 9 is pressed (less than 0 or greater than 9). When OK is pressed, the program picks up where the error occured and keeps going.  (Example, on the 13th value entered, the user input 34.  The program should display the error message box without starting over or ending the program.  once OK is pressed, the program picks up at the 13th entry again).  Currently, when I try this, the final WHILE statement near the end of the program executes (see below). Now, when YES is pressed in that instance, the program DOES pick up, while NO ends the program. How do I get a default MessageBox to display in the other's place - a proper display??

Here's the code. It's workable as-is.  As I stated earlier inthis post, this IS homework.  but, what I'm asking is for my own benefit, not for the instructors. What you see below is eough for them. Thanks in advance for all your assistance in this matter.

#include <iostream.h>
#include <windows.h>
int main()
{

int ProcessedValues = 0;
int Count356 = 0;
int Count149 = 0;

      do
      {
      cout << "Enter a number: " << flush;
      int Number;

      while ((ProcessedValues < 20) && (cin >> Number) && (Number >= 0)
            && (Number <= 9))
            {
            ++ProcessedValues;
            switch (Number)
                  {
                  case 3:
                  case 5:
                  case 6:
                        ++Count356;
                        break;
                  case 1:
                  case 4:
                  case 9:
                        ++Count149;
                        break;
                  }

                  cout << "Number of digits which were 3, 5, or 6: " << Count356
                        << "\n";
                  cout << "Number of digits which were 1, 4, or 9: " << Count149
               << "\n";
                  cout << "Processed Values: " << ProcessedValues << endl;
            }
      }

      while (MessageBox(NULL, "Would you like to process 20 more numbers?", "Again?",
            MB_YESNO | MB_ICONQUESTION)==IDYES);

      PostQuitMessage(0);

return 0;
}

Mike Wonch

PS - I'm using Borland's Turbo C++ 4.5 for Windows compiler for this project.
0
Comment
Question by:MWonch
  • 4
  • 3
8 Comments
 
LVL 7

Accepted Solution

by:
psdavis earned 20 total points
Comment Utility
Part 1:
   Put your ProcessedValues ++ inside of your switch statement so that invalid entries won't get counted.

Part 2:

// Take the MessageBox out of the while statement and convert it to a simple integer check...

int iMessageReturn = IDOK;

do
{
.
   iMessageReturn - MessageBox( NULL, "Text", MB_YESNO... );

}
while( iMessageReturn != IDNO )

// Now you can add your default statement...

switch{
case 1:
.
   ProcessedValues ++;
   Count149 ++;
   break;
.

case 2:
case 7:
case 8:
   cout < "Again?";
   break;

default:
   MessageBox( ... );
   continue;
}

// Here the continue skips over the second messagebox and the while statement is reexecuted successfully.

That should be enough to fancy up your code for your teacher.  I always went the extra mile for all of my projects, so I'm glad to hear that you're doing the same!

Phillip

   
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
No problem.  While we won't do your homework for you, there is no harm in helping you beautify the program a bit.

Hmmm...  somebody already locked the question.
Well, I hate waste so here's the code and you decide which answer you like.

#include <iostream.h>

#define STRICT
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

int main()
{
   
    int ProcessedValues = 0;
    int Count356 = 0;
    int Count149 = 0;
   
    do
    {
        cout << "Enter a number: " << flush;
        int Number;

        // In order to avoid 'goto's we add a flag
        BOOL continueFlag = TRUE;

        while (continueFlag && (ProcessedValues < 20))
        {
            // New line?  Prompt user
            if (cin.peek() == '\n')
                cout << "AGAIN: ";

            cin >> Number;
            ++ProcessedValues;

            switch (Number)
            {
            case 3:
            case 5:
            case 6:
                ++Count356;
                break;

            case 1:
            case 4:
            case 9:
                ++Count149;
                break;

            default:
                // Illegal number?
                if (Number < 0 || Number > 9)
                    if (MessageBox(NULL, "Abort?", "Illegal number", MB_YESNO | MB_ICONQUESTION) == IDYES)
                        continueFlag = FALSE;
            }
           
            // User asked for termination?
            if (continueFlag)
            {
                cout << "Number of digits which were 3, 5, or 6: " << Count356 << "\n";
                cout << "Number of digits which were 1, 4, or 9: " << Count149 << "\n";
                cout << "Processed Values: " << ProcessedValues << endl;
            }
        }

        // Clear input stream
        cin.ignore();
    } while (MessageBox(NULL, "Would you like to process 20 more numbers?", "Again?",
        MB_YESNO | MB_ICONQUESTION) == IDYES);
   
    PostQuitMessage(0); // No need - no message loop.
   
    return 0;
}
0
 

Author Comment

by:MWonch
Comment Utility
WOW! Now, that was not only a fast reply from y'all, but detailed, too! THANKS!

The teacher will not see what I will do - it's for my own benefit only; to learn a bit more.  I do this with all my programs, and my standard dress-ups were getting old (see the MessageBox at the bottom? It's in all my apps in one form or another).  I had a couple of ideas and decided to act upon them.

I was worried, however, that people here would take my code, pronouce my message false (meaning I wanted them to finish it for me for school, not myself), and send me a barrage of flames or reject/ignore my post. I'm really glad you folks helped me out in this.  I will be using what I learn in this program to spruce up others, where appropriate.

Again, thanks! See you all later!!

Mike Wonch
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
Mike, it is really quite simple to distinguish between "I need a program that does..." and "Here's my program, please help me with these problems...".
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

 

Author Comment

by:MWonch
Comment Utility
Alexo,

That's nice you can make that distinction.  You'd be surprised how many do not(or maybe you wouldn't<G>).

Anyway, there is a problem. The first code from the other guy didn't work - at all. It was entered exactly as he had it in a brand new screen - still no dice.  So, I used yours.  Yours worked almost perfectly, as I want it.  The is one thing, though, that I cannot figure out.

You know the ABORT if statement MessageBox? You have the answer either YES or NO, with YES taking the use to the last WHILE MEssageBox asking if (s)he wishes to process another 20 numbers.  Anyway, IDYES works fine.  However, answering NO does not. Answering IDNO counts the error as if it was a valid entry.

So, if we could configure IDNO to simply restate the AGAIN: line for the same line the error occured, this can be wrapped up and I can rest easier. <G>  Or, maybe we can change the ABORT to simply an error MessageBox with OK as the answer, THEN have the program pick up where the error interrupted it (on the same line).

Other than that, your code works EXACTLY as I'd envisioned. Thanks!

In another question, there was one thing I noted that was different from what I'm used to.  If you could explain it, I'll be able to better ascertain where I must go to read up fully.  What is cinpeek() == '\n'?? I tried implementing cin >> '\n' in it's place, but it didn't work. So, I assume it's just different enough to cause errors in this format. That got my curiosity up. <G>

Mike Wonch
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
OK, let's take it one by one.

>> The first code from the other guy didn't work [...] Yours worked almost perfectly [...]
Thing is, you accepted psdavis's answer so he already got the fame, glory, credit and points...  I suggest that the next time you get an answer to your question, just post a comment acknowledging it, test it and then (based on the results of the test) accept it, reject ("reopen") it or ask for more clarifications.

>> Answering IDNO counts the error as if it was a valid entry.
Easily fixed.

First, we change the 'switch' entry thus:

    default:
        // Illegal number?
        if (Number < 0 || Number > 9)
        {
            --ProcessedValues;
            if (MessageBox(...) == IDYES)
                continueFlag = FALSE;
        }

Then we change the condition for displaying the statistics to:

    if (Number >= 0 && Number <= 9)
    {
        // cout << ...
        // cout << ...
        // cout << ...
    }

>> What is cinpeek()
It's cin.peek()
The istream::peek() method returns the next character in the stream WITHOUT extracting it from the stream.  Sort of "what will be the next character I get?"
if (cin.peek() == '\n') checks whether we have reached the end of the line.

0
 

Author Comment

by:MWonch
Comment Utility
I seem to remember someone once mentioned that I can send a note to the administrator of this board about the assignment, or reassignment, of points for questions answered. What or who do I contact regardign this, and I will do so.

I will take your suggestion on trying code first, then returning for the grade.  I know better than this, i really do!<G>

Thanks for the added code.  If you hear nothing more from me, you'll know I'm a happy man!

Mike Wonch
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
You can ask a 0-point "question" in the "Experts Exchange" customer support area requesting reassignment of points.  The EE policy is "Fair" in the sense that they do not deduct points, only add or refund (if justified).

>> If you hear nothing more from me, you'll know I'm a happy man!
Have fun!
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

771 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

14 Experts available now in Live!

Get 1:1 Help Now