Thread: infinite loop after char is entered:

  1. #1
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499

    infinite loop after char is entered:

    I have the program working but when I check if the input to make sure it is not a char it creates a infinite loop. I used an if statement to check for the issue and solve it but its not working. I even tried throwing an exception but I learned later they are not used for things like this.

    Code:
    #include <iostream>
    #include <limits>
    #include "contacts.h"
    
    using namespace std;
    
    int main()
    {
    
        addressBook MyaddressBook;
        
        int userInput=0;
        
    	nodePtr temp=new node;
    
    	string NAME;
        MyaddressBook.userPromptStatement();
    	while(1)
    	{
           
                
      cin>>userInput;
            
            if (userInput!=1||userInput!=2||userInput!=3||userInput!=4)
            {
                cout<<"Only enter a 1,2,3 or 4"<<endl;
                cout<<"You have entered an incorrect value."<<endl;
                cout<<endl<<endl;
                MyaddressBook.userPromptStatement();
            }
            if (isalpha(userInput)) {
                cout<<"ERROR!!!,\n"
                    <<"Only enter a 1,2,3 or 4"<<endl;
                cout<<"\n"<<"\n";
                cin.fail();
                cin.clear();
                MyaddressBook.userPromptStatement();
            }
            else
                switch (userInput) {
                    case 1:
                        cout<<"NAME: ";
                        cin.ignore();
                        getline(cin,temp->name,'\n');
                        cout<<"\nRANK: ";
                        getline(cin,temp->last,'\n');
                        cout<<"\nAGE: ";
                        cin>>temp->age;
                        
                        MyaddressBook.addContact(temp);
                        MyaddressBook.userPromptStatement();
                        cout<<"\n"<<"\n";
                        break;
                    case 2:
                        cout<<"Which contact would you like to delete?\n";
                        cin>>NAME;
                        
                        MyaddressBook.deleteName(NAME);
                        MyaddressBook.userPromptStatement();
                        cout<<"\n"<<"\n";
                        break;
                    case 3:
                        MyaddressBook.editName(NAME);
                        break;
                    case 4:
                        MyaddressBook.printContactList();
                        MyaddressBook.userPromptStatement();
                        cout<<"\n"<<"\n";
                    default:
                        break;
                }
            }
        
        return 0;
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    check state of the stream after you try to input

    Code:
    if(cin >> userInput)
    {
       //process input 
    }
    else
    {
       //get rid of the garbage in the input buffer using cin.ignore()
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    When you try to enter a character into a numeric variable the input stream will fail. When this failure happens the value of the variable is unchanged and no further operations will happen with this stream until you clear the error state and then empty the input buffer of the offending characters. This is why it is usually better to retrieve all user input into a string, then validate and convert this string into your numeric value. Another way of handling this problem is to check the stream state, if it is in an error state, clear the error and empty the buffer.

    Code:
    #include <limits>
    ...
             cin>>userInput;
             while(!cin) {
                cout << "ERROR!!!,\n" << "Only enter a 1,2,3 or 4" << endl;
                cout << "\n" << "\n";
                cin.clear();
                cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // empty input buffer.
                // Re-display your prompt and try to get new user input.
    ..
            }
    
            if (userInput != 1 || userInput != 2 || userInput!=3 || userInput != 4)
     ...
    You also need work on your indentation and a little white space would really help make your program more readable.


    Jim

  4. #4
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Vart:

    I get it now, thanks... Now I have more issues. My C++ class is over but I want to practice more before I jump into my next one "data structure". I am working on a linked list as you can tell and I want to print to a data file. I tired using a while statement inside the case statements but that was a fail. The way I am trying now is not working at all but I am not getting any errors.

    Also my if statements are all executing every time For example:
    Enter 1 to add a new contact: Enter 2 to delete a contact:
    Enter 3 edit Contact:
    Enter 4 to print your address book
    1
    Only enter a 1,2,3 or 4
    You have entered an incorrect value.

    Code:
    #include <iostream>
    #include <fstream>
    #include "contacts.h"
    
    using namespace std;
    
    int main()
    {
    
        addressBook MyaddressBook;
        
        ifstream inFile("/Users/peterjocham/Desktop/textinput.txt");
        if (!inFile) {
            cerr<<"File couldn't be opened";
            exit(EXIT_FAILURE);
        }
        
        int userInput=0;
        
    	nodePtr temp=new node;
    	string NAME;
        MyaddressBook.userPromptStatement();
        
    	while(1)
    	{
      cin>>userInput;
            
            if (userInput!=1||userInput!=2||userInput!=3||userInput!=4)
            {
                cout<<"Only enter a 1,2,3 or 4"<<endl;
                cout<<"You have entered an incorrect value."<<endl;
                cout<<endl<<endl;
                MyaddressBook.userPromptStatement();
            }
            if (cin>>userInput)
            {
                cout<<"ERROR!!!,\n"
                    <<"Only enter a 1,2,3 or 4"<<endl;
                cout<<"\n"<<"\n";
            }
            else
            {
                MyaddressBook.userPromptStatement();
            }
            
                switch (userInput) {
                    case 1:
                        
                            cout<<"NAME: ";
                            cin.ignore();
                            getline(cin,temp->name,'\n');
                            inFile >>temp->name;
                            
                            cout<<"\nLAST NAME: ";
                            getline(cin,temp->last,'\n');
                            inFile >>temp->last;
                            
                            cout<<"\nAGE: ";
                            cin>>temp->age;
                            inFile >>temp->age;
                            
                            MyaddressBook.addContact(temp);
                            MyaddressBook.userPromptStatement();
                            cout<<"\n"<<"\n";
                            break;
                        
                        
                    case 2:
                        cout<<"Which contact would you like to delete?\n";
                        cin>>NAME;
                        
                        MyaddressBook.deleteName(NAME);
                        MyaddressBook.userPromptStatement();
                        cout<<"\n"<<"\n";
                        break;
                    case 3:
                        MyaddressBook.editName(NAME);
                        break;
                    case 4:
                        MyaddressBook.printContactList();
                        MyaddressBook.userPromptStatement();
                        cout<<"\n"<<"\n";
                    default:
                        break;
                }
            }
        
        return 0;
    }



  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Something like
    Code:
        while(1)
        {
            cin>>userInput;
    
            if (!cin || userInput != 1 && userInput != 2 && userInput != 3 && userInput != 4)
            {
                cin.ignore();
                cout<<"Only enter a 1,2,3 or 4"<<endl;
                cout<<"You have entered an incorrect value."<<endl;
                cout<<endl<<endl;
                MyaddressBook.userPromptStatement();
                continue;
            }
            switch (userInput) {
               ...
            }
       }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code:
    (userInput!=1||userInput!=2||userInput!=3||userInput!=4)
    Can you come up with a value of userInput that will make this condition false? (Remember that || means or, specifically inclusive or, so as long as one or more of the individual pieces is true, the whole thing is true.)

  7. #7
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Thank you, I used the || and && incorrectly. Thank you again...

    What about printing to a file? Line 52,56,60 I am trying to print to a file. What am I doing wrong?

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    1. How can you print something to an input stream?

    2. Do you know the difference between the stream extraction operator>> and the stream insertion operator<<?


    Jim

  9. #9
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Code:
      ofstream outfile;
        outfile.open("/Users/peterjocham/Desktop/textoutput.txt",ios::out);
        ifstream infile("/Users/peterjocham/Desktop/textinput.txt",ios::in);
    Code:
                            cout<<"NAME: ";
                            cin.ignore();
                            getline(cin,temp->name,'\n');
                            infile >> temp->name;
                            
                            cout<<"\nLAST NAME: ";
                            getline(cin,temp->last,'\n');
                            infile >> temp->last;
                            
                            cout<<"\nAGE: ";
                            cin>>temp->age;
                            infile >> temp->age;
                            
                            MyaddressBook.addContact(temp);
                            MyaddressBook.userPromptStatement();
                            cout<<"\n"<<"\n";
                            break;
    >> means I am putting it in the file and << means I am reading the file.... Correct?

  10. #10
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    OK OK OK!!!! I was wrong and I figured it out. It was so very simple.....

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Why are you allocating on the heap?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The sum of the numbers entered in a loop
    By alias in forum C Programming
    Replies: 2
    Last Post: 02-26-2012, 08:13 PM
  2. Replies: 3
    Last Post: 10-14-2011, 11:33 PM
  3. comparing an entered value to a char
    By hawaiian_girl in forum C Programming
    Replies: 3
    Last Post: 10-21-2010, 05:28 PM
  4. loop freak out when char entered
    By cerin in forum C++ Programming
    Replies: 7
    Last Post: 04-02-2005, 02:31 AM
  5. Is there any way to prevent a char/int infinite loop?
    By Tokimasa in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2004, 10:14 AM