[英]Read a string line by line using c++
我有一個多行的std::string
,我需要一行一行地閱讀它。 請用一個小例子告訴我如何做到這一點。
例如:我有一個字符串string h;
h 將是:
Hello there.
How are you today?
I am fine, thank you.
我需要在Hello there.
提取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
如果您不想使用流:
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 (!(this_line = out.substr(start)).empty()) {
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;
}
}
我正在尋找可以從字符串返回特定行的函數的一些標准實現。 我遇到了這個問題,接受的答案非常有用。 我也有自己的實現,我想分享一下:
// CODE: A
std::string getLine(const std::string& str, int line)
{
size_t pos = 0;
if (line < 0)
return std::string();
while ((line-- > 0) and (pos < str.length()))
pos = str.find("\n", pos) + 1;
if (pos >= str.length())
return std::string();
size_t end = str.find("\n", pos);
return str.substr(pos, (end == std::string::npos ? std::string::npos : (end - pos + 1)));
}
但是我已經用接受的答案中顯示的實現替換了我自己的實現,因為它使用標准功能並且不太容易出錯..
// CODE: B
std::string getLine(const std::string& str, int lineNo)
{
std::string line;
std::istringstream stream(str);
while (lineNo-- >= 0)
std::getline(stream, line);
return line;
}
兩種實現之間存在行為差異。 CODE: B
從它返回的每一行中刪除換行符。 CODE: A
不會刪除換行符。
我發布我對這個不活躍問題的回答的目的是讓其他人看到可能的實現。
筆記:
我不想要任何類型的優化,而是想要執行在 Hackathon 中給我的任務!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.