Read string from standard input in C++
This post will discuss how to read a string from standard input in C++.
1. Using std::getline
A simple solution is to use the std::getline function, which extracts characters from the input stream and stores them into the specified string until a delimiter is found. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string line; std::getline(std::cin, line); std::cout << line << std::endl; return 0; } |
We can extend the solution to continuously read lines until an empty line is encountered.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string line; while (std::getline(std::cin, line) && !line.empty()) { std::cout << line << std::endl; } return 0; } |
2. Using std::cin
Alternatively, we can use std::cin to read from the standard input. The std::cin represents the standard input stream, in the same way std::cout represents the standard output stream.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> int main() { int i; std::cin >> i; std::cout << i << std::endl; double d; std::cin >> d; std::cout << d << std::endl; std::string s; std::cin >> s; std::cout << s << std::endl; return 0; } |
That’s all about reading a string from standard input in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)