In C++, to get user input string we can use std::getline() function. This function read the characters from the console until we hit enter.
#include
#include
int main() {
std::string name;
std::cout << "Enter your name:";
std::getline(std::cin, name);
std::cout << "Hello, "<< name << "!\n";
return 0;
}
In this example, we first include the necessary header files (iostream and string). We then define a string variable called name to hold the user’s input. We then prompt the user to enter their name using std::cout, and read their input using std::getline(std::cin, name). Finally, we output a greeting message using std::cout.
Note that std::getline() reads input until it encounters a newline character (‘\n’), which is automatically added to the input buffer by the user pressing the Enter key. This means that std::getline() will read the entire line of input entered by the user, including any spaces.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.