在C ++ Primer示例中被控制流执行困惑 [英] confused by control flow execution in C++ Primer example

查看:211
本文介绍了在C ++ Primer示例中被控制流执行困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历C ++ Primer(第5版)。在1.4.4节中有以下示例:

I am going through C++ Primer (5th ed). In section 1.4.4, there is the following example:

#include <iostream>
int main()
{
   // currVal is the number we're counting; we'll read new values into val
   int currVal = 0, val = 0;
   // read first number and ensure that we have data to process
   if (std::cin >> currVal) {
      int cnt = 1; // store the count for the current value we're processing
      while (std::cin >> val) { // read the remaining numbers
         if (val == currVal) // if the values are the same
            ++cnt; // add 1 to cnt
         else { // otherwise, print the count for the previous value
         std::cout << currVal << " occurs " << cnt << " times" << std::endl;
         currVal = val; // remember the new value
         cnt = 1; // reset the counter
      }
   } // while loop ends here
      // remember to print the count for the last value in the file
      std::cout << currVal << " occurs " << cnt << " times" << std::endl;
   } // outermost if statement ends here
   return 0;
}

使用给定输入运行
42 42 42 42 42 55 55 62 100 100 100

When you run it with the given input 42 42 42 42 42 55 55 62 100 100 100

打印

42发生5次

55发生2次

62发生1次

要获得最终输出行

100出现3次

您必须按CTRL + D。然后打印并退出程序。

you must press CTRL+D. Then that is printed and the program exits.

为什么是这样?对我来说,看起来这最后一行应该打印,程序退出与其他人。看来我误解了控制流是如何执行的,有人可以澄清吗?

Why is this? To me, it looks like this last line should be printed and the program exited with the others. It seems I am misunderstanding how the control flow is executed so can someone please clarify?

ps我知道这个输出不正确。 C ++ primer 1.4.4

ps I am aware of this Incorrect output. C++ primer 1.4.4 and C++ Primer fifth edtion book (if statement) is this not correct? However, neither of these explain WHY you must ctrl+d to print the final statement.

推荐答案

这是因为这部分:

while (std::cin >> val)

为了终止读取输入流,必须使用EOF终止,

In order to terminate reading the input stream, you have to terminate it with an EOF, which is supplied by Ctrl-D.

考虑一下: cin 默认情况下跳过空格,输入一个数字,用空格(空格,制表符或换行符)将它分隔开。

Think about it: cin skips over whitespace by default and every time you enter a number you separate it with whitespace (a space, a tab or a newline).

程序如何终止输入? 答案是当它读取一个EOF字符 - 如前所述,由Ctrl-D提供。

这篇关于在C ++ Primer示例中被控制流执行困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆