简体   繁体   中英

How to check if user pressed Enter key ?

#include <stdio.h>
#include <string.h>
#include "formatCheck.h"
int main()
    {
    char input[32];
    char format[32]
    printf("enter your format : ");
    fgets(input,sizeof(input),stdin);
    sscanf(input,"%s",format);
        //my problem
        //if user don't enter format it will exit.
         if()
            {
            return 0;
            }
    }

How can I check if user doesn't input anything (just Enter key). Sorry about English. Thanks.

When user hits only enter, input[0] contains \\n

fgets(input,sizeof(input),stdin);
  if(input[0]=='\n') printf("empty string");

If you read about the scanf family of functions you will see that they returns the number of successfully scanned "items". So if your sscanf call doesn't return 1 then there was something wrong.

您可以检查输入文本的长度是0还是NULL

/* fgets example */
#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [100];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     if ( fgets (mystring , 100 , pFile) != NULL ) //Use this
       puts (mystring);
     fclose (pFile);
   }
   return 0;
}


/* fgets example 2 */
#include <stdio.h>

int main()
{
   FILE * pFile;
   char mystring [100];

   pFile = fopen ("myfile.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     if ( fgets (mystring , 100 , pFile) && input[0]!='\n' ) //Use this
       puts (mystring);
     fclose (pFile);
   }
   return 0;
}

Reference : http://www.cplusplus.com/reference/cstdio/fgets/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM