c语言中fstream用法,c – 在类中使用fstream getline()函数

我正在尝试将包含字典单词的文本文件的行加载到数组对象中.我想要一个数组来保存所有以“a”开头的单词,另一个单词用于“b”…用于表示字母表中的所有字母.

这是我为数组对象编写的类.

#include

#include

#include

using namespace std;

class ArrayObj

{

private:

string *list;

int size;

public:

~ArrayObj(){ delete list;}

void loadArray(string fileName, string letter)

{

ifstream myFile;

string str = "";

myFile.open(fileName);

size = 0;

while(!myFile.eof())

{

myFile.getline(str, 100);

if (str.at(0) == letter.at(0))

size++;

}

size -= 1;

list = new string[size];

int i = 0;

while(!myFile.eof())

{

myFile.getline(str, 100);

if(str.at(0) == letter.at(0))

{

list[i] = str;

i++;

}

}

myFile.close();

}

};

我收到一个错误说:

2 IntelliSense: no instance of overloaded function "std::basic_ifstream<_elem _traits>::getline [with _Elem=char, _Traits=std::char_traits]" matches the argument list d:\champlain\spring 2012\algorithms and data structures\weeks 8-10\map2\arrayobj.h 39

我想这需要我重载getline函数,但我不太确定如何去做或为什么它是必要的.

有什么建议?

解决方法:

处理std :: string的流的函数不是istream的成员函数,而是像这样使用的自由函数. (成员函数版本处理char *).

std::string str;

std::ifstream file("file.dat");

std::getline(file, str);

值得注意的是,有更好的更安全的方法来做你想做的事情:

#include

#include

#include

//typedeffing is optional, I would give it a better name

//like vector_str or something more descriptive than ArrayObj

typedef std::vector<:string> > ArrayObj

ArrayObj load_array(const std::string file_name, char letter)

{

std::ifstream file(file_name);

ArrayObj lines;

std::string str;

while(std::getline(file, str)){

if(str.at(0)==letter){

lines.push_back(str);

}

}

return lines;

}

int main(){

//loads lines from a file

ArrayObj awords=load_array("file.dat", 'a');

ArrayObj bwords=load_array("file.dat", 'b');

//ao.at(0); //access elements

}

不要重新发明轮子;结帐矢量,他们是标准的,将为您节省大量的时间和痛苦.

最后尝试不要使用命名空间std,这对于我不会涉及的一系列原因都是不好的;改为使用std :: std对象作为std :: cout或std :: string的前缀.

标签:c,fstream,getline

来源: https://codeday.me/bug/20190826/1730267.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值