파일을 가져 와서 클래스의 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';
내가 발견 한 또 다른 문제 eof
는 루프 상태에서 확인하고 있다는 것 입니다. 그렇게하지 마십시오 .. iostream :: eof가 루프 조건 (예 :) 내부에서 while (!stream.eof())
잘못된 것으로 간주 되는 이유는 무엇 입니까?
대신 다음과 같이하십시오.
std::stringstream ss{ };
if ( std::ifstream file{ "/Path/To/MyFile.txt" } )
{
std::string input{ };
while ( std::getline( file, input ) )
ss << input << '\n';
}
else
{
std::cerr << "Failed to open file\n";
return 1;
}
std::string line{ };
while ( std::getline( ss, line ) )
std::cout << line << '\n';
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다