How to get the first line of a multi-line string in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <string>

std::string getFirstLine(const std::string& multiLineString) {
    std::istringstream stream(multiLineString);
    
    std::string firstLine;
    std::getline(stream, firstLine);
    
    return firstLine;
}

int main() {
    std::string multiLineString = 
        "First line\n"
        "Second line\n"
        "Third line\n"
        "Fourth line";
    
    std::string firstLine = getFirstLine(multiLineString);
    
    std::cout << "The first line is: " << firstLine << std::endl;
}



 
/*
run:
 
The first line is: First line
 
*/

 



answered Aug 12, 2024 by avibootz

Related questions

1 answer 110 views
1 answer 131 views
1 answer 123 views
1 answer 126 views
1 answer 112 views
1 answer 117 views
1 answer 112 views
...