将std :: string to to struct to struct
假设我有以下我想按下定界符'>'的字符串:
std::string veg = "orange>kiwi>apple>potato";
我希望将字符串中的每个项目放在具有以下格式的结构中:
struct pack_item
{
std::string it1;
std::string it2;
std::string it3;
std::string it4;
};
我知道如何这样做
pack_item pitem;
std::stringstream veg_ss(veg);
std::string veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it1 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it2 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it3 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it4 = veg_item;
:有一种更好的单线方法吗?
Let's say I have the following string that I want to tokenize as per the delimiter '>':
std::string veg = "orange>kiwi>apple>potato";
I want every item in the string to be placed in a structure that has the following format:
struct pack_item
{
std::string it1;
std::string it2;
std::string it3;
std::string it4;
};
I know how to do it this way:
pack_item pitem;
std::stringstream veg_ss(veg);
std::string veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it1 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it2 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it3 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it4 = veg_item;
Is there a better and one-liner kind of way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样的事情:
Something like this:
您不需要中间变量。
您可能需要使该功能成为一个函数,例如运算符>> (使用类似的
运营商<<
)您可以制作一个类型
>>
在字符串中读取到定界符,并在一个语句中读取所有四个元素。那真的是“更好”吗?You don't need an intermediate variable.
You might want to make that a function, e.g.
operator >>
(with a similaroperator <<
)You can make a type who's
>>
reads in a string up to a delimiter, and read all four elements in one statement. Is that really "better"?正如评论中建议的那样,您可以将其用于循环:
如果您的意思是“单线”,那么您可能会讨厌并使用:
As suggested in the comments, you could use a for loop as such:
If you meant "one-liner" in its true sense, then you could be nasty and use:
确实:
顺便说一句,多行代码没有错。对单线的寻求通常是对以正确的方式做事的分心。
Indeed:
BTW, there is nothing wrong with multiple lines of code. The quest for the one-liner is often a distraction to doing things the Right Way™.