0

I want to write an input validation, users can input name with whitespace, if it is null or exceed the maximum array length, it will jmp to the beginning. However, when the input is too long, \n would be left over the second turn, which means scanf_s would receive the value automatically in the second turn. So I imagine is there a method like Java fflush in the inline assembly language to clear keyboard input every turn? This is my code:

char inputName[] = "%20[^\n]";
char name[20];
int  validNum;
_asm{
   startInput:
    lea     eax, name 
    push    eax 
    call    scanf_s //this is the problem part 
    add     esp, 8

   computeLength:
    lea     ebx, name
    ...
    inc     validNum 
    cmp     [ebx], '\0'
    je      validate 

    validate:
    cmp     validNum, 20
    jg      startInput
   }
Gilbert
  • 121
  • 2
  • 13
  • Sorry, this is just my problem, I googled around and could not find what is the specific command and how to use it. – Gilbert Nov 25 '17 at 01:56
  • You push the address of `name` twice, instead of pushing the format string first. Are you sure your code works at all? – Peter Cordes Nov 25 '17 at 02:30
  • I'm not sure `fflush` is what you're looking for. If you want scanf to skip a newline, use a format string of `"\n%20[^\n]"`. If that's your problem, this is a duplicate of https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer. Err, actually that might make scanf eat any whitespace, rather than just an optional newline. – Peter Cordes Nov 25 '17 at 02:32
  • Actually, I want to **check** the array is `null` or ` exceed`, your method works I needn't flush cache because users could input right in the scanf_s part, but I want to validate the array and then jump to the beginning let user reinput. – Gilbert Nov 25 '17 at 03:24
  • 1
    BTW, it's not a "cache", it's a buffer. And BTW, ISO C `fflush( stdin )` (or any other input stream) is undefined behaviour (http://en.cppreference.com/w/c/io/fflush). In POSIX, the behaviour is defined for seekable input files: the underlying file descriptor position is repositioned to match the stdio position. (I.e. it discards the input buffer, along with any `ungetc` data). – Peter Cordes Nov 25 '17 at 03:35
  • According to this: https://stackoverflow.com/questions/18493390/how-and-where-to-use-standard-input-flush-in-java, there's no `fflush` in Java, and `flush()` only makes sense on output streams. – Peter Cordes Nov 25 '17 at 03:37
  • Re: your last update: now you only pass one argument, and still no format string. I assume you meant to implement `scanf_s(inputName, name);`. You should have changed the first `push` to push the address of `inputName`. – Peter Cordes Nov 25 '17 at 03:42

0 Answers0