2011-07-08 63 views
0

我试图通过在文件中的每一行的双端队列中添加一个新条目来从txt文件构建一个字符串(以C++为单位)。下面是我对这个函数的尝试 - 我知道while循环被执行了正确的次数,但是在调用这个函数之后,队列总是空的。我确信我错过了一些小东西(对C++语法和工作非常新颖......),并且非常感谢任何帮助。如何将文本文件读入deque

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); 
     } 
    } 
}   
+0

你可以创建一个流提取运算符重载,而不是.. – AJG85

回答

9

你被传递的队列,不是引用。试试这个:

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

你是对的。谢谢! – rowerguy229

+0

@ rowerguy229由于Nicol的回答有助于解决您的问题,因此点击绿色复选标记将其标记为已接受,这很客气。接受答案还可以使用Stack Overflow声望点奖励您。 –

3

传递deque<string>无论是referencepointer。您正在创建一个本地deque,它在通话结束时超出范围。

1

我建议使用STL为你工作(见working demo on codepad [1]);这一计划将复制自身在stdout:

#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? - 也许这是一个巨大的预编译头,以减少服务器负载)

1

我会从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));