简体   繁体   English

c ++终止while循环,以'|'读取数字

[英]c++ Terminate while loop that reads numbers with '|'

I am currently working through a book on C++ and I am stumped by a very simple problem. 我目前正在研究一本有关C ++的书,但被一个非常简单的问题所困扰。

Trying to write a program that takes in two integers, outputs them, and repeats. 尝试编写一个包含两个整数的程序,将其输出并重复。

What is causing me problems is that the program is supposed to be terminated when '|' 导致我出现问题的原因是该程序应该在“ |”时终止 is entered to the console. 输入到控制台。

I've tried this: 我已经试过了:

(inside of while loop) (在while循环内)

char c;
int a, b;
cin >> c;
a = c;
if (c == '|')
    break
a = c - 48;
cin >> b;
b = c;
if (c == '|')
    break;
b = c - 48;
.....

Obviously this only works for a small range of numeric inputs. 显然,这仅适用于一小部分数字输入。 Is there a better approach that will give me the ability to enter in multidigit numbers and detect if '|' 是否有更好的方法可以使我能够输入多位数并检测'|' has been entered? 已经输入? Apologies if this seems basic, statically typed languages are not my forte. 如果这看起来很基础,抱歉,静态类型语言不是我的专长。

The obvious way would to use a loop, and check the conversion by testing the stream's conversion to bool after reading (or at least, attempting to read): 显而易见的方法是使用循环,并在读取(或至少尝试读取)后测试流向bool的转换来检查转换:

int i;
while (std::cin >> i)         // Try to read a number
    std::cout << i << "\t";   // if successful, print it out

if (std::cin.peek == '|')     // check why reading a number failed.
    // end of input detected
else
    // invalid input detected

I think, you should change your terminating condition. 我认为,您应该更改终止条件。 In that case, if your terminating condition is any non number input (char, string), you can get your expected result (works for integer range of numeric inputs). 在这种情况下,如果终止条件是任何非数字输入(字符,字符串),则可以获得预期的结果(适用于数字输入的整数范围)。

You can try like this... 你可以这样尝试...

...
if (!(cin >> a))
{
    break;
}

if (!(cin >> b))
{
    break;
}
...
//Uncomment the below two lines if you want to take more input
//cin.clear();
//cin.ignore(std::numeric_limits<int>::max(), '\n');

For your understanding 您的理解

if ( !(cin >> vaiable) ) is true, it means that 如果(!(cin >> vaiable))为真,则表示

a) the entered value does not fit the variable a)输入的值不适合变量

b) the variable will not be affected b)该变量将不受影响

c) the stream is still broken c)流仍然中断

d) the entered value is still in the buffer and will be used for the next "cin >> variable" statement. d)输入的值仍在缓冲区中,并将用于下一个“ cin >> variable”语句。


If you want to process further input, do the following: 如果要处理其他输入,请执行以下操作:

a) repair the stream via cin.clear(); a)通过cin.clear()修复流;

b) clear the buffer with cin.ignore(std::numeric_limits::max(),'\\n'); b)使用cin.ignore(std :: numeric_limits :: max(),'\\ n')清除缓冲区;

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

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