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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With