gpt4 book ai didi

c++ - 为什么从文件输入中读取 std::string 会返回空白?

转载 作者:行者123 更新时间:2023-11-28 06:31:03 26 4
gpt4 key购买 nike

我希望从类中返回一个字符串。

我有一个像这样的对象:

.....
using namespace std;
class inputFile{
private:

fstream _file;
bool _exists;
std::string _inFileName; // the filename
std::string _fileContents;

protected:

public:
inputFile(std::string*);
std::string getFileContents();
};

构造函数:

inputFile::inputFile(std::string *in)
{
_inFileName=*in;

_file.open(_inFileName.c_str(),ios_base::in);
while(_file.good()){
getline(_file,_fileContents);

cout << _fileContents << endl;
}

if(_file.is_open())
_exists=true;
else
_exists=false;
}

我返回 _fileContents 的方法总是返回 null 而不是我正在读取的文件内容。这是为什么?

std::string inputFile::getFileContents(){
return _fileContents;
}

驱动.cpp:

meshfile=new inputFile("test.txt")
std::cout << meshFile->getFileContents() << std::endl;

返回空白

最佳答案

您不在 _fileContents 中保存行。你每次都覆盖它。您必须使用 _fileContents.append 或运算符 += 附加每一行。

class inputFile{
private:
fstream _file;
bool _exists;
std::string _inFileName; // the filename
std::string _fileContents;

protected:

public:
inputFile(std::string* in) {
_inFileName = *in;

_file.open(_inFileName.c_str(), ios_base::in);
while (_file.good()) {
std::string line;
getline(_file, line);
_fileContents += line;
}

cout << _fileContents << endl;
}
std::string getFileContents();
};

关于c++ - 为什么从文件输入中读取 std::string 会返回空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27575312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com