Note that there are some explanatory texts on larger screens.

plurals
  1. POFile Reading Class C++
    text
    copied!<p>I am making a file reading class. It should, when constructed open the file with the given string and depending on which constructor is called use the second string supplied to skip through the file to the line after the string given.</p> <p>Here is my code as it stands:</p> <pre><code>SnakeFileReader::SnakeFileReader(string filePath) { fileToRead_.open(filePath.c_str(), ios::in); } SnakeFileReader::SnakeFileReader(string filePath, string startString) { fileToRead_.open(filePath.c_str(), ios::in); string toFind; while (toFind != startString &amp;&amp; !fileToRead_.eof()) { fileToRead_ &gt;&gt; toFind; } } string SnakeFileReader::ReadLine() { string fileLine; if (!fileToRead_.fail() &amp;&amp; !fileToRead_.eof()) fileToRead_ &gt;&gt; fileLine; return fileLine; } int SnakeFileReader::ReadInt() { string fileLine = ""; if (!fileToRead_.fail() &amp;&amp; !fileToRead_.eof()) fileToRead_ &gt;&gt; fileLine; int ret; istringstream(fileLine) &gt;&gt; ret; return ret; } SnakeFileReader::~SnakeFileReader() { fileToRead_.close(); } </code></pre> <p>The problem I have is that in the second constructor I get a segmentation fault. I get another segmentation fault in the read line function as soon as I declare a string.</p> <p>[Edit] Here is the extra code requested. I am making a "Snake Game" as a part of the first year of my degree. I want the game to read and save files rather than hard code variable values. I will finally be using this class a lot to setup a level in the game. However here are a few lines that should demonstrate how i intend to use this class:</p> <pre><code>//Level.cpp std::string fileToRead = "resources/files/level1.txt"; SnakeFileReader sfr(fileToRead); std::string mapFilePath = sfr.ReadLine(); ImageFile(mapFilePath).load(map_layout); mapWidth_ = sfr.ReadInt(); mapHeight_ = sfr.ReadInt(); level_cell_size_ = sfr.ReadInt(); map_ = new TileData*[mapWidth_]; for (int i = 0; i &lt; mapWidth_; i++) { map_[i] = new TileData[mapHeight_]; } </code></pre> <p>Layout of the file:</p> <pre><code>resources/images/Map1_Layout.bmp 40 30 20 </code></pre> <p>Class declaration:</p> <pre><code>#ifndef SNAKE_FILE_READER_HPP #define SNAKE_FILE_READER_HPP #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; using namespace std; class SnakeFileReader { public: SnakeFileReader(string filePath); SnakeFileReader(string filePath, string startString); ~SnakeFileReader(); string ReadLine(); int ReadInt(); private: ifstream fileToRead_; }; #endif // SNAKE_FILE_READER_HPP </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload