简体   繁体   English

C ++在到达输入结束后结束do while循环

[英]C++ End a do while loop after reaching the end of input

I'm trying to write a program that translates input into its binary form using C++. 我正在尝试编写一个程序,使用C ++将输入转换为二进制形式。 However i'm having a bit of problem with the do-while loop portion that continues to translate each additional input. 但是我对do-while循环部分有一些问题,它继续翻译每个额外的输入。 The condition for the do-while loop is messed up so the output becomes an infinite loop. do-while循环的条件混乱,因此输出变为无限循环。

do{
   cin>>number;
   if (number<0)
      cout<< number<< " (base 10) is not a positive integer"<<endl;
   else if (number==0) 
      cout<< number<< " (base 10) = 0 (base 2) ";
   else {
      binary= binaryConverter(number);
      cout<< number << " (base 10) =";
      cout<< binary << " (base 2)";
   }
   cout<< endl;
}while(????);

这将循环直到接收到终止信号(如CTRL-C),然后流终止

while(cin >> number)

The canonical C++ input loop looks like this: 规范的C ++输入循环如下所示:

ItemType item;
while ( input_stream >> item ) {
   // Do something with item, for example:
   //   std::cout << item;  or,
   //   container.push_back(item);  or,
   //   sum += item;  or whatever.
}

That sort of loop will run exactly once per input item, will stop at end-of-file (whether it is the end of a disk file or EOF signaled from the console). 那种循环每个输入项只运行一次,将在文件结束处停止(无论是磁盘文件的末尾还是从控制台发出的EOF信号)。 It will also stop as soon as the input no longer comports to the format of an item (for example, if ItemType is int and the input has the letter Q in it.) 一旦输入不再符合项目的格式,它也将停止(例如,如果ItemTypeint且输入中包含字母Q.)

Specifically, one should never use .eof() or .good() as a loop condition. 具体地,一个应该使用.eof().good()作为一个循环条件。 One should hardly ever use a do-while as the input loop. 人们几乎不应该使用do-while作为输入循环。

In your case, the loop should look like: 在您的情况下,循环应如下所示:

while(std::cin >> number) {
  std::cin>>number;
  if (number<0)
    std::cout<< number<< " (base 10) is not a positive integer";
  else if (number==0) 
    std::cout<< number<< " (base 10) = 0 (base 2) ";
  else {
    binary= binaryConverter(number);
    std::cout<< number << " (base 10) =";
    std::cout<< binary << " (base 2)";
  }
  std::cout<< "\n";
}

Ps I modified your code to conform to two other widely-adopted standards: never say using namespace std; Ps我修改了你的代码以符合其他两个广泛采用的标准:永远不要说using namespace std; and never say std::endl when you mean '\\n' . 当你的意思是'\\n'时,永远不要说std::endl

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

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