简体   繁体   中英

break exits the program - C++

I am C++ beginner, the following program is very simple, yet i don't know why when "EXIT" is entered, the program terminates, though it's supposed to print out the names entered before !

here's the code:

#include <iostream>
#include <string>
#include <set> 

using namespace std;

int main()
{
  set <string> myset;
  set <string> :: const_iterator it;
  it = myset.begin();

  string In;
  int i=1;

  string exit("EXIT");

  cout << "Enter EXIT to print names." << endl;

  while(1)
  {
    cout << "Enter name " << i << ": " ;
    cin >> In;

    if( In == exit)
      break;

    myset.insert(In);
    In.clear();
    i++;
  }


  while( it != myset.end())
  {
    cout << *it << " " ;
    it ++ ;
  }

  cout << endl;
}

thanks in advance.

After you complete your insertions, you need to determine again the beginning of the set:

it = myset.begin();

Should go before the 2nd while loop.


If you are able to use C++11 features, consider using a range-based for loop. Notice that it does not require the use of any iterator:

for( auto const& value : myset )
  std::cout << value << " ";
std::cout << "\n";

If you are not able to use C++11 features, consider a regular for loop. Notice that the scope of the iterator is limited to the for loop:

for(std::set<std::string>::const_iterator it=myset.begin(), end=myset.end(); 
      it != end; ++it)
  std::cout << *it << " ";
std::cout << "\n";
it = myset.begin();

Move this line to just before the loop that displays the names. The problem is that with it at the top, where there are no elements in the set, it gets the value of the end iterator, so the display loop ends immediately.

it == myset.end(); evaluates to true after the first while loop is done executing. You need to add this line of code between the loops it = myset.begin();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM