繁体   English   中英

如何检查用户是否按Enter键?

[英]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;
            }
    }

如何检查用户是否未输入任何内容(只需输入Enter)。 对不起英语。 谢谢。

当用户仅点击回车时, input[0] contains \\n

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

如果您阅读了scanf函数系列,将会看到它们返回成功扫描的“项目”的数量。 因此,如果您的sscanf调用未返回1则说明有问题。

您可以检查输入文本的长度是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;
}

参考: http : //www.cplusplus.com/reference/cstdio/fgets/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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