如何在C++中逐行处理包含换行符的字符串?
C++ 逐行读取字符串中的内容
要实现你想要的逐行读取逻辑,最简洁的方式是借助std::stringstream(需要包含<sstream>头文件),它能把普通字符串包装成输入流,这样就能直接用std::getline来逐行读取,完全匹配你想要的循环写法:
#include <iostream> #include <string> #include <sstream> int main() { std::string message = "Hello\nHow are you?\nGood!"; std::string line; std::stringstream ss(message); // 用getline循环读取每一行 while (std::getline(ss, line)) { // 这里处理每一行内容,比如打印输出 std::cout << "读取到行:" << line << std::endl; } return 0; }
如果不想用getline,也可以手动分割字符串后用范围for循环遍历——先把所有行存入std::vector<std::string>容器,再逐个处理:
#include <iostream> #include <string> #include <vector> std::vector<std::string> split_string(const std::string& s, char delimiter) { std::vector<std::string> lines; std::string current_line; for (char c : s) { if (c == delimiter) { lines.push_back(current_line); current_line.clear(); } else { current_line += c; } } // 加入最后一行(避免字符串不以换行结尾时丢失内容) if (!current_line.empty()) { lines.push_back(current_line); } return lines; } int main() { std::string message = "Hello\nHow are you?\nGood!"; auto lines = split_string(message, '\n'); // 范围for循环遍历每一行 for (const auto& line : lines) { std::cout << "读取到行:" << line << std::endl; } return 0; }
两种方法里,stringstream的方式更贴合C++标准用法,代码简洁且不易出错,推荐优先使用。
内容的提问来源于stack exchange,提问作者Ziv Sion
相关产品推荐
相关产品推荐

