[英]break exits the program - C++
我是C ++初学者,下面的程序非常简单,但我不知道为什么当输入“EXIT”时,程序终止,虽然它应该打印出之前输入的名字!
这是代码:
#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;
}
提前致谢。
完成插入后,需要再次确定集合的开头:
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";
it = myset.begin();
将此行移动到显示名称的循环之前。 问题是,如果它在顶部,集合中没有元素,它将获得结束迭代器的值,因此显示循环立即结束。
it == myset.end();
在第一个while循环执行完毕后,计算结果为true
。 你需要在循环之间添加这行代码it = myset.begin();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.