Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
On Windows, the following returns an empty string when the enter key is hit without any other input:
C++
string input;
cin.clear();
getline(cin, input);
But on WSL/Ubuntu, compiled with gcc, a bare enter key does nothing. It must be preceded by a space to get getline to return.

What I have tried:

The frequently used
C++
getline(cin, input, '\n');
makes no difference. I've done net searches trying to find something about this, but no luck.
Posted
Updated 15-Jun-22 5:45am
v4

Following works as expected for me:
C++
#include <iostream>

using namespace std;

int main()
{
    string input;
    cin.clear();
    getline(cin, input);
    cout << input.length() << '\n';
}
Which prints 0 when only the enter key is hit. That's a fairly old WSL 1 instance on a VmWare Windows 10 system, but I'd be surprised if things have changed between WSL 1 and WSL 2. If the above does not work, then either MS has bungled WSL, or there's something odd with your WSL instance. If it does work for you, then it suggest that there's something going on elsewhere in your program.
 
Share this answer
 
Comments
Greg Utas 15-Jun-22 5:59am    
Curious.
Greg Utas 15-Jun-22 6:44am    
I tried that as the first thing in my main but still the same result.

On an unrelated(?) topic, I have a test that kills a runaway thread with ctrl-C. It works on Windows but not on WSL2/Ubuntu. There is no sign of the ctrl-C getting forwarded to the Linux Console Window that VS2022 creates as a tab.
k5054 15-Jun-22 12:05pm    
I just tried this within VS, rather than compiling directly on the ubuntu WSL instance, and get the same behavior as you do in the "Linux Console Window" that VS gives you. But running the VS compiled executable on the Linux host (in this case a Pi, but assume its the same on an Ubuntu WSL instance), the executable performs as expected, I.E. a bare return works as expected. So it's something that VS is doing in the Console Window. Bleah. Presumably whatever that is is eating the CTL-C too. All I can suggest at the moment is to try running the program from an Ubuntu console, rather than the VS Linux Console Window.
Just tested it with WSL2 on Win10. As a result gets one a blocking function.
After going without further input RETURN has entered, the length 0 is displayed.
Exactly the same thing happens on Windows with VS, but requires as include additionally <string>.

Output of uname -a
Linux XXPC10 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900