Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break exits the program - C++

Tags:

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.

like image 766
Nour Avatar asked Nov 16 '12 19:11

Nour


2 Answers

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";
like image 198
Robᵩ Avatar answered Sep 18 '22 09:09

Robᵩ


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.

like image 32
Pete Becker Avatar answered Sep 20 '22 09:09

Pete Becker