【问题标题】:Easiest way to get words of one line from istream into a vector?将 istream 中的一行单词转换为向量的最简单方法?
【发布时间】:2011-06-21 03:00:51
【问题描述】:

istream>> 运算符,但它会像跳过空格一样跳过新行。如何将仅 1 行中的所有单词的列表放入向量(或任何其他方便使用的内容)中?

【问题讨论】:

    标签: stl istream c++


    【解决方案1】:

    一种可能性(虽然比我想要的要详细得多)是:

    std::string temp;
    std::getline(your_istream, temp);
    
    std::istringstream buffer(temp);
    std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
                                    std::istream_iterator<std::string>());
    

    【讨论】:

    • 它看起来很冗长。 (但是,嘿,我问的是 C++。)为什么使用 std::copy 而不是 Foo Bah 的 for 循环?
    • @MTsoul:主要是因为我更喜欢使用算法,除非它们完全疯了(尽管我承认这与它的边界......)
    • 你不需要std::copy()。使用std::vector的构造函数。
    • @Jerry:在 VS2010 中,第 5 行有警告 C4930,并且该行未编译。我试图理解它,但没有办法。
    • @Michael Smith:哎呀——最令人头疼的解析又来了。现在应该修好了……
    【解决方案2】:

    我建议使用getline 将行缓冲到string,然后使用stringstream 来解析string 的内容。例如:

    string line;
    getline(fileStream, line);
    
    istringstream converter(line);
    for (string token; converter >> token; )
        vector.push_back(token);
    

    小心在 C++ 中使用 C 字符串读取函数。 std::string I/O 函数更安全。

    【讨论】:

      【解决方案3】:

      你可以调用 istream::getline -- 会读入一个字符数组

      例如:

      char buf[256];
      cin.getline(buf, 256);
      

      如果您想对行中的各个令牌使用流兼容的访问器,请考虑使用 istringstream

      【讨论】:

        猜你喜欢
        • 2011-02-13
        • 2012-02-05
        • 2017-06-18
        • 1970-01-01
        • 2012-09-02
        • 2011-10-08
        相关资源
        最近更新 更多