C++ 如何从 std::string 做“getline”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13838065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do "getline" from a std::string?
提问by user1873947
I have a problem. I load the whole file and then getline through it to get some info. However in the map format there may be 0 or 20 "lines" with the info. I need to know how to getline through std::string. There is a function (source stream, destination string, decimal) but I need (source string, destination string, decimal). Searching in streams isn't possible in C++ (only using many temp string and extracting and inserting many times, it's unclear and I don't want to do it that messy way). So I want to know how to getline from a std::string.
我有个问题。我加载整个文件,然后通过它获取一些信息。然而,在地图格式中,信息可能有 0 或 20 条“行”。我需要知道如何通过 std::string 获取线路。有一个函数(源流、目标字符串、十进制)但我需要(源字符串、目标字符串、十进制)。在 C++ 中无法在流中进行搜索(仅使用许多临时字符串并多次提取和插入,目前尚不清楚,我不想以那种凌乱的方式进行)。所以我想知道如何从 std::string 获取行。
Thans
比
回答by Some programmer dude
You seem to want std::istringstream
, which is in the header <sstream>
:
你似乎想要std::istringstream
,它在标题中<sstream>
:
std::string some_string = "...";
std::istringstream iss(some_string);
std::string line;
while (std::getline(iss, line))
{
// Do something with `line`
}