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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rcrean13
    New Member
    • Jun 2019
    • 4

    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?

    Code:
    // Handle exceptions by fixing the errors. The program continues to
    // prompt the user until a valid input is entered.
    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
    	int number;
    	bool done = false;
    	string str =
    		"The input stream is in the fail state."; 
    	do 
    	{ 
    		try 
    		{ 
    			cout << "Line 8: Enter an integer: "; 
    			cin >> number; 
    			cout << endl; 
    			if (!cin) 
    				throw str; 
    			done = true; 
    			cout << "Line 14: Number = " << number
    				<< endl; 
    		} 
    		catch (string messageStr) 
    		{ 
    			cout << "Line 18: " << messageStr
    				<< endl; 
    			cout << "Line 19: Restoring the "
    				<< "input stream." << endl; 
    			cin.clear(); 
    			cin.ignore(100, '\n'); 
    		} 
    	} while (!done); 
    	return 0; 
    }
    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:
    Last edited by rcrean13; Jun 11 '19, 03:57 PM.
  • zmbd
    Recognized Expert Moderator Expert
    • Mar 2012
    • 5501

    #2
    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.

    Comment

    • rcrean13
      New Member
      • Jun 2019
      • 4

      #3
      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?

      Comment

      • dev7060
        Recognized Expert Contributor
        • Mar 2017
        • 656

        #4
        What IDE/platform are you using? I have tested the code in Dev-C++ and CodeBlocks, everything works fine.

        Comment

        • rcrean13
          New Member
          • Jun 2019
          • 4

          #5
          Interesting...I 'm using Microsoft Visual Studio with windows 10. I'll see about testing it again.

          Comment

          • rcrean13
            New Member
            • Jun 2019
            • 4

            #6
            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...

            Comment

            • zmbd
              Recognized Expert Moderator Expert
              • Mar 2012
              • 5501

              #7
              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)

              Code:
              #include<iostream>
              #include<limits>
              using namespace std;
              
              int main()
              {
                int zNumber;
                bool zGo = true;
              
                
                while(zGo)
                {
                  cout << "Enter an integer: ";
                  cin >> zNumber;
                  if(cin.fail())
                  {
                    cin.clear();
                    cin.ignore(numeric_limits<streamsize>::max(),'\n');
                    cout << "Sorry, you need an integer value" << endl;
                  } else
                  {
                    zGo = false;
                  }
                }
                 
                cout << "The Number is: " << zNumber << endl;
                return 0;
              }
              (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.
              Last edited by zmbd; Jun 13 '19, 12:49 AM.

              Comment

              • Arjunkumar1
                New Member
                • Apr 2021
                • 2

                #8
                Used https://www.interviewbit.com/online-cpp-compiler/ It was all fine.

                Comment

                Working...