Note that there are some explanatory texts on larger screens.

plurals
  1. POstring size is different on Windows than on Linux
    text
    copied!<p>I stumbled upon strange behavior of <strong>string::substr</strong>. Normally I code on <strong>Windows 7</strong> in Eclipse+MinGW, but when I was working on my laptop, using Eclipse in <strong>Linux</strong> (Ubuntu 12.04) I noticed difference in result.</p> <p>I was working with <strong>vector&lt; string ></strong> filled with lines of text. One of steps was to remove last character from line.</p> <p>In win7 Eclipse I did:</p> <pre><code>for( int i = 0; i &lt; (int)vectorOfLines.size(); i++ ) { vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-1) ); } </code></pre> <p>and it works like intended (removing last character from each line)</p> <p>But in Linux this code do not trim. Instead I needed to do it like this:</p> <pre><code>// -2 instead -1 character vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-2) ); </code></pre> <p>or using another method:</p> <pre><code>vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).replace( (((string)vectorOfLines.at(i)).size()-2),1,"",0 )); </code></pre> <p>Ofcourse Linux methods work wrong way on windows (trimming 2 last characters, or replacing one before last).</p> <p>The problem seems to be that myString.size() return number of characters in Windows, but in Linux it returns number of characters + 1. Could it be that new line character is counted on Linux?</p> <p>As a newbie in C++ and programming general, I wonder why it is like that, and how can this be done to be platform independent.</p> <p>Another thing that I wonder is : which method is preferable (faster) <strong>substr</strong> or <strong>replace</strong>?</p> <p>Edit: Method used to fill string s this function i wrote:</p> <pre><code>vector&lt; string &gt; ReadFile( string pathToFile ) { // opening file ifstream myFile; myFile.open( pathToFile.c_str() ); // vector of strings that is returned by this function, contains file line by line vector&lt; string &gt; vectorOfLines; // check if the file is open and then read file line by line to string element of vector if( myFile.is_open() ) { string line; // this will contain the data read from current the file while( getline( myFile, line ) ) // until last line in file { vectorOfLines.push_back( line ); // add current line to new string element in vector } myFile.close(); // close the file } // if file does not exist else { cerr &lt;&lt; "Unable to open file." &lt;&lt; endl; // if the file is not open output //throw; } return vectorOfLines; // return vector of lines from file } </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