'Reading multi line inputs in C++
I'm trying to read multiple lines of input from the command line in C++ and store them into an array. This is my code.
std::string line;
int in;
std::vector<std::string> v;
while(std::getline(std::cin, line)){
if(line == "^D") break;
v.push_back(line);
}
for(auto it = v.begin(); it != v.end(); it++){
std::cout<<*it<<std::endl;
}
The stdin goes into an infinite loop and I can't seem to figure out how to prevent that. Basically the behavior targeted is that two consecutive press of enter without any input should terminate the stdin loop and run the program.
Solution 1:[1]
I would test to see if the string is empty. If so, break. Like this:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(){
string line;
vector<string> v;
while(std::getline(cin, line)){
if (line.empty()){
break;
}
v.push_back(line);
}
vector<string>::iterator it;
for (it = v.begin(); it != v.end(); it++){
cout << *it << '\n';
}
return 0;
}
Solution 2:[2]
If you really want the loop to stop with two Enter's, you can change the conditional to
if(line == "" && v.size() >= 1 && v.back() == "") break;
Which should check if the current keystroke and the previous one were Enter's. The v.size() >= 1 is just to check whether v has any elements in it, and to stop a Segfault if it doesn't have any other elements.
Do note that the last element in the array will be an empty string, and if you want to get rid of that, just write
v.pop_back();
outside of the first loop, which gets rid of the last element.
Solution 3:[3]
the while loop could look like this, with use of .empty() only:
while(std::getline(cin, line)){
if(line.empty() && !v.empty() && v.back().empty()) {
v.pop_back(); // remove the last empty line
break;
}
v.push_back(line);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt |
| Solution 2 | Kamal Sadek |
| Solution 3 | andzun |
