String has contents even though there is no input from user

后端 未结 4 1670
长情又很酷
长情又很酷 2021-01-29 02:50

I am trying to \"trap\" keyboard inputs from user, meaning the code will prevent them from entering certain characters, which in this case prevents the input of numbers and spec

相关标签:
4条回答
  • 2021-01-29 03:03

    Memory always contains something. The space used by your variable contains something, and calling strlen() on that just so happens not to blow up somewhere.

    Note that the operating system usually reads a full line (and allows editing it), shipping it to the reading application only on ENTER. To handle this is significatly harder than plain reading. Are you sure that it isn't good enough to get a line, check it and complain or go ahead?

    0 讨论(0)
  • 2021-01-29 03:04

    since your buffe will get memory on stack it will contain some garbage value you better initialize it with zero or better way is to use memset() function.

    0 讨论(0)
  • 2021-01-29 03:10

    Reading uninitialised variables like done to buffe here:

    if (c1=='\r' && strlen(buffe)==0)
    

    provokes undefined behaviour, anything could happen afterwards. Do not do this.

    Always initialise variable before reading them.

    In this case you might like to simply do:

    char buffe[32] = "";
    

    or (as already proposed by others) the more generic way:

    char buffer[32] = {0};
    

    More complicated but also valid would be to do:

    char buffer[32];
    strcpy(buffe, "");
    

    or

    char buffer[32];
    memset(buffe, 0, sizeof(buffe));
    
    0 讨论(0)
  • 2021-01-29 03:12

    May be try

    char buffe[30] = {0};
    

    (I have not tried this thouggh)

    0 讨论(0)
提交回复
热议问题