C++ User Input
Include the following code to read user input in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string userInput;
cout << "Enter your input: ";
getline(cin, userInput);
cout << "You entered: " << userInput << endl;
return 0;
}
- The
#include <iostream>
line allows you to perform input and output operations. #include <string>
provides functionality for string handling.using namespace std;
allows you to use items in the standard C++ library.- In the
main()
function,string userInput;
declares a variable to store the user input. cout << "Enter your input: ";
displays a message asking for input.getline(cin, userInput);
reads a line of text from the user and assigns it to theuserInput
variable.cout << "You entered: " << userInput << endl;
displays the entered input.return 0;
ends the program.