Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>scanf</code> function works this way per the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/scanf.html" rel="nofollow">specification</a>:</p> <blockquote> <p>An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is <strong>an initial subsequence of a matching sequence.</strong> [Emphasis added.]</p> </blockquote> <p>In your example, the following C string represents the contents of <em>stdin</em> when the first <code>scanf</code> call requests input: <code>"4.4\n"</code>.</p> <p>For this initial call, your format string consists of a single specifier, <code>%d</code>, which represents an integer. That means that the function will read as many bytes as possible from <em>stdin</em> which satisfy the definition of an integer. In your example, that's just <code>4</code>, leaving <em>stdin</em> to contain <code>".4\n"</code> (if this is confusing for you, you might want to check out <a href="http://en.wikipedia.org/wiki/Integer" rel="nofollow">what an integer is</a>).</p> <p>The second call to <code>scanf</code> does not request any additional input from the user because <em>stdin</em> already contains <code>".4\n"</code> as shown above. Using the format string <code>%f</code> attempts to read a floating-point number from the current value of <em>stdin</em>. The number it reads is <code>.4</code> (per the specification, <code>scanf</code> disregards whitespace like <code>\n</code> in most cases).</p> <p>To fully answer your question, the problem is not that you're misusing <code>scanf</code>, but rather that there's a mismatch between what you're inputting and how you're expecting <code>scanf</code> to behave.</p> <p>If you want to guarantee that people can't mess up the input like that, I would recommend using <code>strtol</code> and <code>strtod</code> in conjunction with <code>fgets</code> instead.</p>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    1. This table or related slice is empty.
    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