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.
I would test to see if the string is empty. If so, break. Like this:
#include <string>
#include <vector>
#include <iostream>
int main(){
std::string line;
std::vector<std::string> v;
while(std::getline(std::cin, line)){
if (line.empty()){
break;
}
v.push_back(line);
}
std::vector<std::string>::iterator it;
for (it = v.begin(); it != v.end(); it++){
std::cout << *it << '\n';
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With