Note that there are some explanatory texts on larger screens.

plurals
  1. POExtra File lines being overwritten when output is put into specificied file lines
    text
    copied!<p>Hey I have a bit of a silly question but I am having a bit of an issue with my code. I am trying to overwrite a line of a file, which is what it does, but the problem is that it overwrites other file lines as well. I am using C++ visual studios 2010. My code is below. </p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; using namespace std; const string FILENAME = "DatabaseTest.txt"; fstream&amp; GoToLineI(fstream&amp; file, int num) { file.seekg(ios::beg); for(int i = 0; i &lt; num+1; i++) file.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); return file; } fstream&amp; GoToLineO(fstream&amp; file, int num) { file.seekp(ios::beg); for( int i = 0; i &lt; num; i++) { //gets the length of the line. GoToLineI(file, i); string s; file &gt;&gt; s; long pos = file.tellp(); file.seekp( pos + s.length() ); } return file; } int main() { fstream myfile(FILENAME.c_str(), ios::out); myfile.close(); myfile.open(FILENAME.c_str(), ios::in | ios::out); myfile &lt;&lt; "Usernames:" &lt;&lt; endl; for( int j = 0; j &lt; 101; j++) myfile &lt;&lt; j &lt;&lt; endl; cout &lt;&lt; "Where do you want to grab the data from?"; int i = 0; cin &gt;&gt; i; GoToLineI(myfile, i); string line; myfile &gt;&gt; line; cout &lt;&lt; line &lt;&lt; endl; GoToLineO(myfile, i); if( myfile.is_open() ) { cout &lt;&lt; "File should be writeable" &lt;&lt; endl; myfile &lt;&lt; "This should be at line 75" &lt;&lt; endl; } myfile.seekp(ios::end); system("PAUSE"); myfile.close(); return 0; } </code></pre> <p>The issue may be in how I have my GoToLineO, which is how I find where to get to the output line, and It calls the GoToLineI in order to get the length of the lines until it reaches the right line to start displaying out put on. The output that this code generates is as such.</p> <pre><code>72 73 74 This should be at line 75 82 83 84 </code></pre> <p>And it should look like this:</p> <pre><code>73 74 This should be at line 75 76 77 78 79 80 81 </code></pre> <p>Any sort of insights or advice would be greatly appreciated.</p> <p>edit: changed to only the important part of the outputs that should be shown. </p>
 

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