read full line in c++
To read a full line in C++, you can use the getline()
function from the <iostream>
library. Here's an example of how to use it:
#include <iostream>
#include <string>
int main() {
std::string line;
std::cout << "Enter a line of text: ";
std::getline(std::cin, line);
std::cout << "You entered: " << line << std::endl;
return 0;
}
Let's break down the steps involved in this code:
- Include the necessary headers:
cpp #include <iostream> #include <string>
- The
<iostream>
header provides input/output functionality. The
<string>
header provides thestd::string
class for working with strings.Declare a variable to store the line of text:
cpp std::string line;
We create a
std::string
variable namedline
to store the input.Prompt the user for input:
cpp std::cout << "Enter a line of text: ";
The
std::cout
statement displays the prompt message to the user.Read the line of text using
getline()
:cpp std::getline(std::cin, line);
The
std::getline()
function reads a line of text from the standard input (in this case,std::cin
) and stores it in theline
variable.Display the input:
cpp std::cout << "You entered: " << line << std::endl;
The
std::cout
statement outputs the entered line of text along with a message.Return 0 to indicate successful program execution:
cpp return 0;
That's it! This code will allow you to read a full line of text in C++ using the getline()
function.