Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is that you're mixing the <code>&gt;&gt;</code> operator with calls to <code>getline</code>. Generally, you want to use one or the other, but not both of them together.</p> <p>The reason you get an empty string in your vector is because <code>&gt;&gt;</code> will NOT consume the whitespace which causes it to stop. That is, it reads the <code>"5"</code>, finds the newline character after it, and then stops, leaving the newline character in the <code>ifstream</code>.</p> <p>Then, the call to <code>getline</code> encounters the newline character and immediately says, "Done! I read a line!". It consumes the newline character and returns the entire string leading up to it -- which in this case was the empty string.</p> <p>If you know that your data will be formatted properly (no invalid input), it might be easiest just to use <code>&gt;&gt;</code> to read the entire file. Otherwise, I would recommend using <code>getline</code> to read each line one at a time, then using a <code>stringstream</code> object to parse the data out of the line.</p> <p><strong>EDIT</strong></p> <p>I just noticed that the rest of your input has first/last names separated by spaces. Since <code>&gt;&gt;</code> stops on spaces, it would probably be easiest to use <code>getline</code> to read the entire file. Example of reading the <code>5</code>:</p> <pre><code>string line; getline(fin, line); stringstream converter; converter &lt;&lt; line; int n; converter &gt;&gt; n; </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