如何读取文本文件到deque [英] How to read text file into deque

查看:139
本文介绍了如何读取文本文件到deque的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在文件中的每一行的deque中添加一个新的条目,从txt文件中构造字符串deque(在C ++中)。下面是我对该函数的尝试 - 我知道while循环正在执行正确的次数,但是在调用此函数后,队列总是为空。我相信我缺少一些小的(非常新的C ++语法和工作...),任何帮助是非常感激。

  void read_file(string file_name,deque< string> str_queue){
ifstream filestr;
filestr.open(file_name);
if(!filestr.is_open()){
perror(打开文件时出错。
}
else {
while(filestr){
string s;
getline(filestr,s);
str_queue.push_back(s);
}
}
}


解决方案>

您通过 value 传递队列,而不是引用。尝试这样:

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


I am trying to construct a deque of strings (in C++) from a txt file by putting a new entry in the deque for each line in the file. Below is my attempt at the function - I know that the while loop is being executed the proper number of times, however after calling this function the queue is always empty. I'm sure I'm missing something small (very new to C++ syntax and workings...), and any help is greatly appreciated.

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

解决方案

You are passing the queue by value, not by reference. Try this:

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

这篇关于如何读取文本文件到deque的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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