Home > OS >  get multiple lines of strings from input in c
get multiple lines of strings from input in c

Time:11-09

I just wrote a programme for something and I have to get several lines of string from user but I could not handle it. for example: the inputs are "ajflskahnlkanjf" and "jhsagfalifsbk" in two lines and my code should find some pattern in them. the pattern part is handled but I can not get strings in several lines. By the way the user should first give me the lines of strings and then my code should start processing.

using namespace std;

int main()
{
    string str;
    getline(cin, str);
    std::regex const pattern("ab c");
    for (std::string const text :
         {
             str,
         }) //
    {
        std::smatch match;
        for (auto it = text.cbegin(), e = text.cend();
             std::regex_search(it, e, match, pattern); it = match[0].second) {
            std::cout << "Match: " << match.str() << "\n";
        }
    }
}

CodePudding user response:

If I understood you correctly, the problem is that you read only one line of the input, when there might be an unknown number of them. The idiomatic way to read lines until the EOF signal is received is

std::string line;
while (std::getline(std::cin, line)) {
    // The code for processing the line goes here
}

However, if you know exactly the number of the lines you need to read, you can do

int nlines = 2; // For example
std::vector<std::string> lines;
lines.reserve(2); // A small optimization
while (nlines--) {
    std::string line;
    std::getline(std::cin, line);
    lines.push_back(std::move(line)); // Move to avoid copying. The line becomes 
                                      // invalid from here, remove the move if you will 
                                      // plan to do something else with it
}
// Process the lines in the vector outside the loop
  •  Tags:  
  • c
  • Related