How to deal with EOF ?

This is a discussion on How to deal with EOF ? within the C++ Programming forums, part of the General Programming Boards category; I thought it would be simple.. but couldn't come up with a solution. How would I stop the following program ...

  1. #1
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498

    How to deal with EOF ?

    I thought it would be simple.. but couldn't come up with a solution.
    How would I stop the following program from entering an Infinite loop when it gets an eof ?
    Code:
    #include<iostream>
    #include<string>
    int main()
    {
        std::string str;
        while(true)
        {
            std::cout<<"Input: ";
            std::getline(std::cin,str);
            std::cout<<str<<std::endl;
        }
        return 0;
    }
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,032
    Well one way is to use exceptions:
    Code:
    cin.exceptions (ios::eofbitif||ios::failbit | ios::badbit)
    Another way is a simple break:
    Code:
    if(!std::getline(std::cin,str)) break;
    Last edited by King Mir; 12-02-2011 at 05:43 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deal or No Deal arrays
    By shel5210 in forum C Programming
    Replies: 2
    Last Post: 03-31-2010, 01:40 AM
  2. Deal or No Deal Proogram
    By shel5210 in forum C Programming
    Replies: 1
    Last Post: 03-28-2010, 08:04 PM
  3. Deal or No Deal listbox prob
    By kryptkat in forum Windows Programming
    Replies: 5
    Last Post: 03-30-2009, 06:53 PM
  4. Replies: 5
    Last Post: 09-18-2008, 02:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21