I have just started learning C++, and have wrote this simple while
loop program which is meant to ask the user to input their name until it has been given an input which isn’t empty:
#include <iostream>
#include <string>
int main() {
std::string Name;
while(Name.empty()){
std::cout << "nEnter name: ";
std::getline(std::cin>>std::ws, Name);
}
std::cout << "Hello, " << Name;
return 0;
}
However, when the user gives the input an empty value into the variable, instead of printing another line of "Enter name: "
, it just moves the cursor down another line within the terminal.
How can I get it where another line of "Enter name: "
is outputted every time the while
loop iterates?
I have tried to use r
and n
.
5
A basic solution to the problem would be to simply remove the >>std::ws
part from your std::getline
call. This makes it print the Enter name:
string after just pressing enter.
However, this would consider a name made purely of whitespaces to be valid, which you would have to check for. If you want to strip (trim) the string, there is this for some convenience functions.
If you want to just keep it simple, use a basic for loop.
Full code:
#include <iostream>
#include <string>
int main() {
std::string Name;
bool is_whitespace = true;
while (Name.empty() || is_whitespace) {
std::cout << "nEnter name: ";
std::getline(std::cin, Name);
for (int i = 0; i < Name.length(); i++) {
const auto substring = Name.at(i);
if (substring != ' ') {
is_whitespace = false;
break;
}
}
}
std::cout << "Hello, " << Name;
return 0;
}
Hope I could help!