c ++ splitlines
To split a string into lines in C++, you can use the std::istringstream
class and the std::getline
function. Here are the steps to accomplish this:
- Include the necessary headers:
#include <sstream>
#include <vector>
- Declare a string variable to store your input string:
std::string inputString;
- Read the input string from the user:
std::getline(std::cin, inputString);
- Declare a
std::istringstream
object and initialize it with the input string:
std::istringstream iss(inputString);
- Declare a vector to store the individual lines:
std::vector<std::string> lines;
- Use a while loop to read each line from the
std::istringstream
and store it in the vector:
std::string line;
while (std::getline(iss, line)) {
lines.push_back(line);
}
- Now, the
lines
vector contains each line of the input string as separate elements.
Here's the complete code snippet:
#include <sstream>
#include <vector>
#include <iostream>
int main() {
std::string inputString;
std::getline(std::cin, inputString);
std::istringstream iss(inputString);
std::vector<std::string> lines;
std::string line;
while (std::getline(iss, line)) {
lines.push_back(line);
}
// Use the 'lines' vector as needed
for (const auto& line : lines) {
std::cout << line << std::endl;
}
return 0;
}
This code will split the input string into separate lines and store them in a vector. You can then use the lines
vector to process or display each line separately.