用制表符分隔的文本填充字符串向量 [英] populating a string vector with tab delimited text

查看:121
本文介绍了用制表符分隔的文本填充字符串向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手。

我正在尝试使用制表符分隔文件中的元素填充矢量。最简单的方法是什么?

I'm trying to populate a vector with elements from a tab delimited file. What is the easiest way to do that?

谢谢!

推荐答案

这可能是最简单的方法,但vcp的方法可能更有效。

This is probably the easiest way to do it, but vcp's approach can be more efficient.

std::vector<string> tokens;
std::string token;
while (std::getline(infile, token, '\t')
{
    tokens.push_back(token);
}

完成。实际上,您可以使用输入迭代器后插入器,但是为什么呢?

Done. You can actually get this down to about three lines of code with an input iterator and a back inserter, but why?

现在,如果将文件切成几行并用这些行上的制表符隔开,则还必须处理

Now if the file is cut up into lines and separated by tabs on those lines, you also have to handle the line delimiters. Now you just do the above twice, one loop for lines and an inner loop to parse the tabs.

std::vector<string> tokens;
std::string line;
while (std::getline(infile, line)
{
    std::stringstream instream(line)
    std::string token;
    while (std::getline(instream, token, '\t')
    {
        tokens.push_back(token);
    }
}

d如果您需要做线,然后制表符,然后...我不知道...引号?三个循环。但是老实说,我可能正在研究编写状态机。我怀疑您的老师在现阶段想要这样的事情。

And if you needed to do line, then tabs, then... I dunno... quotes? Three loops. But to be honest by three I'm probably looking at writing a state machine. I doubt your teacher wants anything like that at this stage.

这篇关于用制表符分隔的文本填充字符串向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆