Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have to be careful when mixing <code>operator&gt;&gt;</code> with <code>getline</code>. The problem is, when you use <code>operator&gt;&gt;</code>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since <code>operator&gt;&gt;</code> is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you call <code>getline</code>, a newline character is the only thing it's looking for. Since that's the first thing in the buffer, it finds what it's looking for right away, and never needs to prompt the user.</p> <p>Fix: If you're going to call <code>getline</code> after you use <code>operator&gt;&gt;</code>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call to <code>getline</code>.</p> <p>Another option, and this is along the lines of what Martin was talking about, is to not use <code>operator&gt;&gt;</code> at all, and only use <code>getline</code>, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:</p> <pre><code>int getInt(std::istream &amp; is) { std::string input; std::getline(is,input); // C++11 version return stoi(input); // throws on failure // C++98 version /* std::istringstream iss(input); int i; if (!(iss &gt;&gt; i)) { // handle error somehow } return i; */ } </code></pre> <p>You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:</p> <pre><code>cin &gt;&gt; i; </code></pre> <p>You do this:</p> <pre><code>i = getInt(cin); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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