× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to read time with scanf() in C

Dan Connolly
Nov 17, 2014
<p>Suppose you want to read a structured value, such as a time with hour, minute, and second. In C, <a href="http://en.wikipedia.org/wiki/Scanf_format_string">scanf() format strings</a> are quite handy:</p><pre><code class="language-cpp">#include &lt;stdio.h&gt; struct time { int hour; int minute; int second; }; int main() { struct time when; int items; printf("Enter a time expressed as hh:mm:ss format.\n"); items = scanf("%02d:%02d:%02d", &amp;when.hour, &amp;when.minute, &amp;when.second); if (items == 3) { printf("You entered: %d hours %d minutes %d seconds\n", when.hour, when.minute, when.second); } else { printf("oops!"); } } </code></pre><p>Note:</p><ul><li><strong>scanf()</strong> breaks the input into parts and converts strings to integers for us</li><li><strong>scanf()</strong> needs the address of a variable (e.g. <strong>&amp;when.hour</strong> rather than just <strong>when.hour</strong>) in order to store something there</li></ul>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus