read string with spaces in c++
To read a string with spaces in C++, you can use the getline()
function from the <string>
library. This function allows you to read a line of text, including spaces, from the input stream. Here's how you can use it:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a string with spaces: ";
std::getline(std::cin, input);
std::cout << "You entered: " << input << std::endl;
return 0;
}
Explanation:
Include the necessary libraries:
cpp #include <iostream> #include <string>
These lines include the necessary libraries to work with input/output and strings in C++.Declare a variable to store the input:
cpp std::string input;
This line declares astd::string
variable namedinput
to store the user's input.Prompt the user for input:
cpp std::cout << "Enter a string with spaces: ";
This line uses thestd::cout
object to print a prompt message asking the user to enter a string with spaces.Read the input using
getline()
:cpp std::getline(std::cin, input);
This line uses thestd::getline()
function to read a line of text from the input stream (std::cin
) and store it in theinput
variable.Display the input:
cpp std::cout << "You entered: " << input << std::endl;
This line uses thestd::cout
object to print the input that the user entered.Return from the
main()
function:cpp return 0;
This line indicates the end of themain()
function, and it returns the value0
to the operating system, indicating successful program execution.
By using the getline()
function, you can read a string with spaces in C++ and store it in a std::string
variable for further processing or display.