2

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.

1
  • 1
    Apart from the I/O concern, you are aware that your loop ASSUMES arr has at least counter+1 elements and will have undefined behaviour if arr has only counter elements? Commented Nov 17, 2020 at 11:18

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

cin.get() removes input from cin. You might want to use peek instead. cplusplus.com/reference/istream/istream/peek

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.