c ++何时停止 [英] c++ when will while(cin>>s) stop

查看:46
本文介绍了c ++何时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手.很抱歉,如果这个问题重复出现,但是我找不到类似的问题.

I'm new to C++. I'm sorry if this question is duplicated but I just can't find similar question.

非常基本的代码:

string s;
while (cin >> s)
    cout << s << endl;

当我按下键盘上的return键时,我希望循环停止.但是它永远不会停止...

I expect the loop stop when I press the return in my keyboard. But it never stop....

我知道cin在遇到无效输入时会返回false,例如,如果我们使用

I know that cin will return false when it encounters invalid input, for example if we use

int i;
while (cin >> i)
    cout << i << endl;

然后,当我们输入非整数时,循环结束.

then the loop ends when we enter a non-integer.

但是在使用字符串的情况下,我们如何停止该循环?

But in case of string, how can we stop that loop?

推荐答案

while(cin>> s){...} 将在输入有效的情况下循环.尝试输入失败时,它将退出循环.

while (cin >> s) { ... } will loop as long as the input is valid. It will exit the loop when the attempted input fails.

有两个可能的失败原因:

There are two possible reasons for failure:

  1. 无效输入
  2. 文件尾

假设输入本身是有效的,为了终止循环,输入流必须到达末尾.

Assuming that the input itself is valid, in order to terminate the loop the input stream has to reach the end.

当输入实际上是一个文件时,识别结尾很容易:当字符用完时,它位于文件的结尾.当它是控制台时,并不是那么容易:您必须做些人造的事情来指示输入的结束.

When the input is actually a file, recognizing the end is easy: when it runs out of characters it's at the end of the file. When it's the console, it's not so easy: you have to do something artificial to indicate the end of the input.

这样做,您必须告诉终端应用程序(控制控制台)不再有输入,然后终端应用程序将告诉您的程序它在输入的末尾.

Do that, you have to tell the terminal application (which controls the console) that there is no more input, and the terminal application, in turn, will tell your program that it's at the end of the input.

您的操作方式取决于终端应用程序,终端应用程序通常是操作系统的一部分.

The way you do that depends on the terminal application, which is typically part of the operating system.

  • Windows 上, ctrl-Z 告诉终端应用程序您位于输入的结尾.
  • Unix系统上,它是 ctrl-D .
  • On Windows, ctrl-Z tells the terminal application that you're at the end of your input.
  • On Unix systems, it's ctrl-D.

这篇关于c ++何时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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