Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multi line inputs in C++

Tags:

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.

like image 444
Antithesis Avatar asked May 11 '26 18:05

Antithesis


1 Answers

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;
}
like image 167
Matt Avatar answered May 14 '26 07:05

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!