简体   繁体   English

在整数数组中输入时如何在 C++ 中按下“输入”时中断循环

[英]How to break a loop when "enter" is pressed in C++ while taking input in an integer array

I have this loop, where arr is an integer array.我有这个循环,其中arr是一个整数数组。

for(int i=0; i<=counter;i++)
    {
        cin>>arr[i];
    }

I'm giving input like this我正在提供这样的输入

2 4 6 7

I want when enter is pressed after 7, just break this loop.我想要在 7 之后按下 Enter 时,只需打破这个循环。


I think it can be done with something like我认为可以用类似的东西来完成

if(cin.get()=="\n")

But I can't understand how to implement it here in this code.但我无法理解如何在这段代码中实现它。

If you wanted to exit your for loop when you press the Enter Key.如果您想在按下 Enter 键时退出 for 循环。 You would need to check the given input before putting it in your array.在将其放入数组之前,您需要检查给定的输入。

And if it is equal to '\\n' , leave the for loop with break .如果它等于'\\n' ,则将 for 循环保留为break

for (int i = 0; i <= counter; i++) {
    // Check if user pressed the Enter Key
    if(std::cin.peek() == '\n') {
        // Leave the for loop
        break;
    }
    std::cin >> arr[i];
}

To ensure that the input doesn't get cleared from cin.get() we can instead use cin.peek() .为了确保输入不会从cin.get()清除,我们可以改用cin.peek()

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

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