-2

I run the following snippet of code expecting that when i hit the new line (Enter key), the program will halt, but it does not do that, any idea what's the problem ? Thanks.

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s ;
    while(getline(cin ,s)){
        cout << s << endl ; 
    }
}
Dromlio
  • 11
  • 1
  • 4
    That will keep going until it reaches **end of file**. Usually there is a key combination to invoke that from the keyboard device like `Ctrl-D` (don't know about Windows). – Galik Nov 08 '18 at 21:10
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h –  Nov 08 '18 at 21:11
  • If you want it to stop after you hit the enter key then why put it in a loop? – Galik Nov 08 '18 at 21:11
  • @Galik i am reading from the standard input, how to skip the loop when encountering a new line ? – Dromlio Nov 08 '18 at 21:12
  • ctrl-z in windows ctrl-d in unix – drescherjm Nov 08 '18 at 21:12
  • @Dromlio By default the standard input is usually attached to the keyboard device. You can avoid that by **piping** input from another program or redirecting input from a file. – Galik Nov 08 '18 at 21:13
  • "expecting that when i hit the new line (Enter key), the program will halt" - that's exactly what it does, until you enter another line of text, And by "halt" do you mean "pause" or "exit"? –  Nov 08 '18 at 21:13
  • Why did you choose to use the `while()` construct? What were you hoping that would do? – Galik Nov 08 '18 at 21:16
  • Get rid of the loop (just call `getline` once) and it will do what you want. – Kevin Nov 08 '18 at 21:18

2 Answers2

3

Hitting the Enter key ends a line. If there’s no other text on the line it’s an empty line, but a line nonetheless.

There are a couple of ways you can handle this.

First, depending on your OS, either ctrl-D or ctrl-Z will act like end-of-file, and the call to getline will fail, ending the loop.

Second, if you want an empty line to end the loop, just check for it:

while (getline(cin, s) && s.length() != 0)
    std::cout << s << '\n';
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

Pressing enter is like entering an empty line, you didn't put any condition for your program to exit. It will stay in infinity unless you forcefully exit it. Implement an exit condition in the while(), so that when it is not met, the loop will exit, and obviously put the getline() inside to keep asking prompting for input.

Mostafa Elgayar
  • 345
  • 1
  • 3
  • 14