【问题标题】:How to read text file into deque如何将文本文件读入双端队列
【发布时间】:2011-07-08 21:24:09
【问题描述】:

我正在尝试通过在文件中的每一行的双端队列中放置一个新条目,从 txt 文件构造一个字符串双端队列(在 C++ 中)。下面是我对该函数的尝试 - 我知道 while 循环正在执行正确的次数,但是在调用此函数后,队列始终为空。我确定我遗漏了一些小东西(对于 C++ 语法和工作原理来说非常新......),非常感谢任何帮助。

void read_file(string file_name, deque<string> str_queue) {
    ifstream filestr;
    filestr.open(file_name);
    if (!filestr.is_open()){
        perror ("Error opening file.");
    }
    else {
        while (filestr) {
            string s;
            getline(filestr,s);
            str_queue.push_back(s);
        }
    }
}        

【问题讨论】:

  • 你可以创建一个流提取运算符重载来代替......

标签: c++


【解决方案1】:

您通过而不是引用传递队列。试试这个:

void read_file(const string &file_name, deque<string> &str_queue) {

【讨论】:

  • @rowerguy229 由于 Nicol 的回答有助于解决您的问题,因此请单击绿色复选标记将其标记为已接受。接受答案还会奖励您 Stack Overflow 信誉积分。
【解决方案2】:

通过referencepointer 传递deque&lt;string&gt;。您正在创建一个本地 deque,它在通话结束时超出范围。

【讨论】:

    【解决方案3】:

    我建议使用 STL 为您工作(请参阅 working demo on codepad[1]);该程序将在标准输出上复制自身:

    #include <iostream>
    #include <fstream>
    #include <iterator>
    #include <deque>
    #include <vector>
    
    using namespace std;
    
    struct newlinesep: ctype<char>
    {
        newlinesep(): ctype<char>(get_table()) {}
    
        static ctype_base::mask const* get_table()
        {
            static vector<ctype_base::mask> rc(ctype<char>::table_size,ctype_base::mask());
            rc['\r'] = rc['\n'] = ctype_base::space;
            return &rc[0];
        }
    };
    
    int main()
    {
        deque<string> str_queue;
    
        ifstream ifs("t.cpp");
        ifs.imbue(locale(locale(), new newlinesep));
        copy(istream_iterator<string>(ifs), istream_iterator<string>(), back_inserter(str_queue));
        copy(str_queue.begin(), str_queue.end(), ostream_iterator<string>(cout, "\n"));
        return 0;
    }
    

    灌输自定义语言环境(newlinesep)的想法是从这个答案中借用的:Reading formatted data with C++'s stream operator >> when data has spaces


    [1] 有趣的是,这告诉了我们很多关于 codepad.org 的实现细节;我不仅猜到了使用的源文件名(t.cpp),而且我们可以看到源代码被稍微修改了(prelude.h? - 也许它是一个巨大的预编译头文件以减少服务器负载)

    【讨论】:

      【解决方案4】:

      我将从previous question 的答案之一开始。在我的回答中,我给出了一个使用std::set 的示例和一个使用std::vector 的示例,但是如果您改用std::deque,代码应该可以继续正常工作:

      std::deque<std::string> lines;
      
      std::copy(std::istream_iterator<line>(std::cin), 
                std::istream_iterator<line>(),
                std::back_inserter(lines));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多