在类中使用fstream getline()函数
Using the fstream getline() function inside a class
我正在尝试将包含字典单词的文本文件的行加载到数组对象中。我想要一个数组来容纳所有以"a"开头的单词,另一个数组代表"b"。。。对于字母表中的所有字母。
这是我为数组对象编写的类。
#include <iostream>
#include <string>
#include <fstream>
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<char>]" matches the argument list d:champlainspring 2012algorithms and data structuresweeks 8-10map2arrayobj.h 39
我想这需要我重载getline函数,但我不太确定如何进行,也不太确定为什么有必要这样做。
有什么建议吗?
处理std::string的流函数不是istream的成员函数,而是一个自由函数。(成员函数版本处理char*)。
std::string str;
std::ifstream file("file.dat");
std::getline(file, str);
值得注意的是,有更好、更安全的方法可以这样做:
#include <fstream>
#include <string>
#include <vector>
//typedeffing is optional, I would give it a better name
//like vector_str or something more descriptive than ArrayObj
typedef std::vector<std::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
}
不要重新发明轮子;结账矢量它们是标准的,将为您节省大量时间和痛苦。
最后尽量不要放在using namespace std
中,这是不好的,原因有很多,我不会深入;相反,在std对象前面加上std::,就像std::cout或std::string一样。
http://en.cppreference.com/w/cpp/container/vectorhttp://en.cppreference.com/w/cpp/string/basic_string/getlinehttp://en.cppreference.com/w/cpp/string
相关文章:
- getline 函数似乎在 C++ 中不起作用
- 如何以及何时使用 getline 函数执行计算?
- 对c++中的输入使用getline函数时忽略第一个字符
- 使用 c++ 中的 getline 函数连续读取两行
- 此C Getline函数的C 代码有什么问题
- 使用 getline 函数读取文件,但第一列显示为空
- 使用 getline 函数获取分段错误
- getline函数只读取第一行
- c++getline函数不允许我输入
- 使用getline函数时出现问题
- 如何正确使用标准::getline函数
- C++:将带有空格的cin转换为不带getline函数的字符串
- 而循环构造与 getline 函数相结合,一直持续到 EOF
- 使用 getline 函数的最优雅方式
- 使用 getline 函数解析 C++ 中的字符串
- 我们如何在程序中同时使用 cin 和 getline 函数
- std::getline函数(fstream _Lock())出错
- 验证输入和getline()函数
- **编译器错误** - getline() 函数不接受第一个参数"std:ifstream"是什么我的问题?
- c++中的Getline()函数需要少一个输入