Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would approach it as follows:</p> <ul> <li>Create a class that represents the name-value pair</li> <li>Use <code>std::istream&amp; operator&gt;&gt;( std::istream &amp;, NameValuePair &amp; );</code></li> </ul> <p>You can then do something like:</p> <pre><code>ifstream inifile( fileName ); NameValuePair myPair; while( ifstream &gt;&gt; myPair ) { myConfigMap.insert( myPair.asStdPair() ); } </code></pre> <p>If your ini file contains sections, each of which contains named-value pair, then you need to read to end-of-section so your logic would not be using stream failure but would use some kind of abstract factory with a state machine. (You read something then determine what it is thus determining your state).</p> <p>As for implementing the stream read into your name-value pair it could be done with getline, using the quote as a terminator.</p> <pre><code>std::istream&amp; operator&gt;&gt;( std::istream&amp; is, NameValuePair &amp; nvPair ) { std::string line; if( std::getline( is, line, '\"' ) ) { // we have token up to first quote. Strip off the = at the end plus any whitespace before it std::string name = parseKey( line ); if( std::getline( is, line, '\"' ) ) // read to the next quote. { // no need to parse line it will already be value unless you allow escape sequences nvPair.name = name; nvPair.value = line; } } return is; } </code></pre> <p>Note that I did not write into nvPair.name until we had fully parsed the token. If the streaming failed we don't want to partially write.</p> <p>The stream will be left in a fail state if either getline failed. This will happen naturally at end-of-file. We don't want to throw an exception if it fails for that reason because that is the wrong way to handle end-of-file. You could throw if it fails between the name and the value, or if the name did not have the trailing = sign (but is not empty) because that is not a natural occurrence. </p> <p>Note that this allows spaces and even newlines between the quotes. Whatever is between them is read other than another quotes. You would have to use an escape sequence to allow those (and parse the value).</p> <p>If you used \" as the escape sequence then when you get the value you must "loop" if it ends with a \ (as well as changing it to a quote), and concatenate them together.</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