2012-11-16 44 views
5

我是C++初學者,下面的程序很簡單,但我不知道爲什麼當輸入「EXIT」時,程序終止,但它應該打印出之前輸入的名字!break退出程序 - C++

下面的代碼:

#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; 
} 

在此先感謝。

回答

3
it = myset.begin(); 

移動此行只顯示名稱循環之前。問題在於,在頂端,在集合中沒有元素的地方,它獲取結束迭代器的值,所以顯示循環立即結束。

+0

感謝它工作:) – Nour

4

後您完成插入,則需要再次確定集的開頭:

it = myset.begin(); 

第二while循環之前應該去。


如果您能夠使用C++ 11功能,請考慮使用基於範圍的for循環。請注意,它不需要使用任何迭代器:

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

如果您無法使用C++ 11功能,請考慮使用常規for循環。注意,迭代器的範圍僅限於for循環:

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

是的,它工作:))謝謝你! – Nour

+0

@ user1830651 - 不客氣。請記住在所有幫助你的答案上點擊「向上」(點擊向上的三角形),然後「接受」(點擊複選標記)答案,最能回答你的問題。 –

0

it == myset.end();在第一個while循環完成執行後評估爲true。你需要在循環之間添加這行代碼it = myset.begin();