Ответ 1
#include <sstream>
#include <iostream>
int main() {
std::istringstream f("line1\nline2\nline3");
std::string line;
while (std::getline(f, line)) {
std::cout << line << std::endl;
}
}
У меня есть std::string
с несколькими строками, и мне нужно читать его по строкам.
Пожалуйста, покажите мне, как это сделать с помощью небольшого примера.
Пример: у меня есть строка string h;
h будет:
Hello there.
How are you today?
I am fine, thank you.
Мне нужно как-то извлечь Hello there.
, How are you today?
и I am fine, thank you.
.
#include <sstream>
#include <iostream>
int main() {
std::istringstream f("line1\nline2\nline3");
std::string line;
while (std::getline(f, line)) {
std::cout << line << std::endl;
}
}
Существует несколько способов сделать это.
Вы можете использовать std::string::find
в цикле для '\n'
символов и substr() между позициями.
Вы можете использовать std::istringstream
и std::getline( istr, line )
(возможно, самый простой)
Вы можете использовать boost::tokenize
это поможет вам: http://www.cplusplus.com/reference/iostream/istream/getline/
Если вы не хотите использовать потоки:
#include <string>
using std::string;
int main() {
string out = "line1\nline2\nline3";
size_t start = 0;
size_t end;
while (1) {
string this_line;
if ((end = out.find("\n", start)) == string::npos) {
if (out.back() != '\n') {
this_line = out.substr(start);
printf("%s\n", this_line.c_str());
}
break;
}
this_line = out.substr(start, end - start);
printf("%s\n", this_line.c_str());
start = end + 1;
}
}