473,246 Members | 1,349 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

String will not output from catch block inside do/while loop

After a user inputs a char value for number two times, I do not receive any output when the program attempts to output the value of messageStr from within the catch block. It appears to be an empty string. Why?

From attempting to output the value of str at various locations, I think that somehow the value for str is being deleted after the first time through the loop. I don't know why this would happen. For some reason, including the initialization for str from inside the do/while loop works, as does including it in the global scope. But putting it inside the main() function scope appears not to work.

Ideas?

Expand|Select|Wrap|Line Numbers
  1. // Handle exceptions by fixing the errors. The program continues to
  2. // prompt the user until a valid input is entered.
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6. int main()
  7. {
  8.     int number;
  9.     bool done = false;
  10.     string str =
  11.         "The input stream is in the fail state."; 
  12.     do 
  13.     { 
  14.         try 
  15.         { 
  16.             cout << "Line 8: Enter an integer: "; 
  17.             cin >> number; 
  18.             cout << endl; 
  19.             if (!cin) 
  20.                 throw str; 
  21.             done = true; 
  22.             cout << "Line 14: Number = " << number
  23.                 << endl; 
  24.         } 
  25.         catch (string messageStr) 
  26.         { 
  27.             cout << "Line 18: " << messageStr
  28.                 << endl; 
  29.             cout << "Line 19: Restoring the "
  30.                 << "input stream." << endl; 
  31.             cin.clear(); 
  32.             cin.ignore(100, '\n'); 
  33.         } 
  34.     } while (!done); 
  35.     return 0; 
  36. }
Here is the output I am getting as an example:

Line 8: Enter an integer: q

Line 18: The input stream is in the fail state.
Line 19: Restoring the input stream.
Line 8: Enter an integer: q

Line 18:
Line 19: Restoring the input stream.
Line 8: Enter an integer:
Jun 10 '19 #1
7 4128
zmbd
5,501 Expert Mod 4TB
Posting a bunch of code without providing a full explanation of what YOU have done to troubleshoot the code, what you were expecting the result to be, and what the result you obtained isn't likely to receive much help...

Maybe if you fill in the blanks?

I've compiled and ran your code... works as written from what I can tell.
Jun 11 '19 #2
Sorry, I was in a rush to post it. I have updated it to be a little bit more clear I hope.

Thanks for the help but I still don't understand why I'm getting the result I am.

Any thoughts on my results?
Jun 11 '19 #3
dev7060
626 Expert 512MB
What IDE/platform are you using? I have tested the code in Dev-C++ and CodeBlocks, everything works fine.
Jun 12 '19 #4
Interesting...I'm using Microsoft Visual Studio with windows 10. I'll see about testing it again.
Jun 12 '19 #5
Using Visual Studio, https://www.onlinegdb.com/online_c++_compiler, and http://cpp.sh/

I've gotten the same erroneous results for all of them...
Jun 12 '19 #6
zmbd
5,501 Expert Mod 4TB
rcrean13:
Looking at your updated post and reviewing the code, it appears to be doing what you want...

Referring to the line numbers in the posted code
Explicit declaration "Number" as integer
Explicit declaration "Str" as string

Line 14 is our try
Line 20 is our throw str
Line 25 is our catch

In your post you enter the alpha "q"

Prompt and fetch at line 16/17
From your post you enter a value of "q"
cin >> Number
The cin goes to an fail state (0) and "Number" = 0
(cin.Fail() = 1)
Line 19 if (!cin)
#19 = if (!0)...
#19 = if (true)...
leading to line 20 where you throw to Line 25 catch
where you loop back

etc...

there are other ways of writing this type of code... for example using the cin.fail()

(air code follows)

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<limits>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.   int zNumber;
  8.   bool zGo = true;
  9.  
  10.  
  11.   while(zGo)
  12.   {
  13.     cout << "Enter an integer: ";
  14.     cin >> zNumber;
  15.     if(cin.fail())
  16.     {
  17.       cin.clear();
  18.       cin.ignore(numeric_limits<streamsize>::max(),'\n');
  19.       cout << "Sorry, you need an integer value" << endl;
  20.     } else
  21.     {
  22.       zGo = false;
  23.     }
  24.   }
  25.  
  26.   cout << "The Number is: " << zNumber << endl;
  27.   return 0;
  28. }
(line 18 isn't mine, I found that snippet somewhere and it works a charm)
You'll still get stupid things like "123abc" or "123.456" returning the value of "123". To stop this one would need to perhaps consider using a string data type for the input value and then code to validate/strip unwanted characters or loop it back to fetch the proper input.
Jun 13 '19 #7
Arjunkumar1
2 2Bits
Used https://www.interviewbit.com/online-cpp-compiler/ It was all fine.
Sep 7 '21 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Roy Smith | last post by:
The following code appears to be illegal: while ((int c = getchar()) != EOF) { putchar (c); } I tried it on two different compilers (Sun workshop and gcc), and both give some variation on...
6
by: foolmelon | last post by:
If a childThread is in the middle of a catch block and handling an exception caught, the main thread calls childThread.Abort(). At that time a ThreadAbortException is thrown in the childThread. ...
9
by: Cybex | last post by:
I am trying to get this to work but when ever I enter an proper integer it just hangs. The Switch default seems to catch the improper integers but the right ones are not triggering the way I...
1
by: Prabhua | last post by:
hi all, can anybody solve my probelm in asp.net using c#. i am creating button inside while loop at runtime in html page.i just want to give different ID for different button inside while...
11
by: Rene | last post by:
Quick question, what is the point for forcing the semicolon at the end of the while statement? See example below: x = 0; do { x = x + 1; }while (x < 3); What's the point of having the...
9
by: somenath | last post by:
Hi All, I have doubt regarding how compiler understands about while loop. For example the bellow mentioned code produce the output as mentioned bellow. #include<stdio.h> int main(void) {
16
by: HillBilly | last post by:
This is freaking me out. I'm using Membership and trying to determine if the database is online. The GetConnectionString( ) method returns a connection string as expected but not when used in the...
5
by: sgurukrupagmailcom | last post by:
Hi, I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here: class Exc { Exc () { System.out.println ("Haribol"); }
5
by: erictheone | last post by:
so here is my code. My getlines for the strings keyword and phrase at lines 44 and 79 respectively don't work. Please help!!! #include <cstdlib> #include <string> #include <iostream> #include...
9
by: saravanan82 | last post by:
Hi All, I tried to execute follwoing program, which got killed by the OS. #include<stdlib.h> main() { while(1) { char *c=(char*)malloc(10000); } }
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.