Soumalya Bhattacharya
Soumalya Bhattacharya

Reputation: 674

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.

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.


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.

Upvotes: 2

Views: 4088

Answers (1)

IndieGameDev
IndieGameDev

Reputation: 2974

If you wanted to exit your for loop when you press the Enter Key. 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.

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().

Upvotes: 2

Related Questions