c - Taking formatted input : sscanf not ignoring white spaces -


i have find out input hours , minutes after taking inputs user of form :

( number1 : number2 )  

eg: ( 12 : 21 )

i should report 12 hours , 21 minutes , again wait input. if there mismatch in given format, should report invalid input. wrote code :

#include<stdio.h> int main() {     int hourinput=0,minutesinput=0;      char *buffer = null;     size_t size;          {         puts("\nenter current time : ");         getline ( &buffer, &size, stdin );          if ( 2 == sscanf( buffer, "%d:%d", &hourinput, &minutesinput ) && hourinput >= 0 && hourinput <= 24 && minutesinput >=0 && minutesinput <= 60  )         {              printf("time : %d hours %d minutes", hourinput, minutesinput );         }          else         {             puts("\ninvalid input");         }        }      while ( buffer!=null && buffer[0] != '\n' );      return 0; } 

q. if gives spaces between number , :, program considers invalid input, while should treat valid.

can explain why happening , idea rid of issue ? far understand, sscanf should ignore white spaces ?

to allow optional spaces before ':', replace

"%d:%d" 

with

"%d :%d" 

sscanf() ignores white space format directives tell ignore, not everywhere. whitespace character in directive such ' ' ignore white spaces. %d other integer , floating point directives ignore leading white space. space before %d redundant.

c11 7,21,6,2,8 input white-space characters (as specified isspace function) skipped, unless specification includes [, c, or n specifier.)


additional considerations include using %u , unsigned alternate way not accept negative numbers. strptime() common function used scanning strings time info.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -