我写了一个程序,把一个文件读入一个类中的stringstream字段,现在我正在尝试与它交互。问题是,从几个方法顺序读取时,其中一个方法给出了错误,或者干脆不起作用。我猜问题是我如何阅读文件,我应该如何改进它?
这是我的课:
class MatReader
{
protected:
...
stringstream text;
...
string PhysicsMaterial;
string Diffuse;
string NMap;
string Specular;
public:
/// <summary>
/// Read all lines in .mat document by string
/// </summary>
void ReadAllLines(string file_path);
/// <summary>
/// Getting PhysicsMaterial property
/// </summary>
string getPhysMaterial();
/// <summary>
/// Getting diffuse file path
/// </summary>
string getDiffuseLocation();
};
这是我的实现文件:
#include "MaterialHandler.h"
void MatReader::ReadAllLines(string mat_file)
{
ifstream infile(mat_file);
string str;
if (infile.is_open())
{
ofile = true;
while (!infile.eof())
{
getline(infile, str);
text << str+"\n";
}
}
else
throw exception("[ERROR] file does not exist or corrupted");
}
string MatReader::getPhysMaterial()
{
string line;
vector<string> seglist;
try
{
if (ofile == false)
throw exception("file not open");
while (getline(text, line, '"'))
{
if (!line.find("/>"))
break;
seglist.push_back(line);
}
for (uint16_t i{}; i < seglist.size(); i++)
{
if (seglist[i-1] == " PhysicsMaterial=")
{
PhysicsMaterial = seglist[i];
return seglist[i];
}
}
line.clear();
seglist.clear();
}
catch (const std::exception& ex)
{
cout << "[ERROR]: " << ex.what() << endl;
return "[ERROR]";
}
}
string MatReader::getDiffuseLocation()
{
string line;
vector<string> seglist;
try
{
if (ofile == false)
throw exception("file not open");
while (getline(text, line, '"'))
{
seglist.push_back(line);
}
for (uint16_t i{}; i < seglist.size(); i++)
{
if (seglist[i - 1] == " File=")
{
PhysicsMaterial = seglist[i];
return seglist[i];
}
}
}
catch (const std::exception& ex)
{
cout << "[ERROR]: " << ex.what() << endl;
return "[ERROR]";
}
}
方法“getPhysMaterial()”和“getDiffuseLocation()”单独工作没有任何问题,但如果按顺序执行,它们会给出一个错误或根本不执行。谢谢。
因此,首先需要纠正超范围数组访问的问题。下一个问题是需要重置流的位置,以便从一开始重新读取它。
下面是一个如何做到这一点的例子。
std::stringstream ss{ };
ss << "This is line one\n"
<< "This is line two\n"
<< "This is line three\n"
<< "This is line four\n";
// Points to the start of the stringstream.
// You can store this as a member of your class.
const std::stringstream::pos_type start{ ss.tellg( ) };
std::string line{ };
while ( std::getline( ss, line ) )
std::cout << line << '\n';
// Reset to the start of the stringstream.
ss.clear( );
ss.seekg( start );
while ( std::getline( ss, line ) )
std::cout << line << '\n';