简体   繁体   English

break退出程序 - C ++

[英]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 ! 我是C ++初学者,下面的程序非常简单,但我不知道为什么当输入“EXIT”时,程序终止,虽然它应该打印出之前输入的名字!

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. 应该在第二个while循环之前去。


If you are able to use C++11 features, consider using a range-based for loop. 如果您能够使用C ++ 11功能,请考虑使用基于范围的for循环。 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. 如果您无法使用C ++ 11功能,请考虑使用常规for循环。 Notice that the scope of the iterator is limited to the for loop: 请注意,迭代器的范围仅限于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();

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. 在第一个while循环执行完毕后,计算结果为true You need to add this line of code between the loops it = myset.begin(); 你需要在循环之间添加这行代码it = myset.begin();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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