C语言 如何检查用户是否按下了 Enter 键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19852303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:55:11  来源:igfitidea点击:

How to check if user pressed Enter key ?

cstringuser-input

提问by Barbiyong

#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.

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

回答by niko

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

当用户点击仅进入时, input[0] contains \n

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

回答by Some programmer dude

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

如果您阅读有关scanf函数系列的内容,您将看到它们返回成功扫描的“项目”的数量。因此,如果您的sscanf电话没有返回,1则说明有问题。

回答by awesum

you can check if the length of input text is 0 or NULL.

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

回答by Sahil Sareen

/* 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/

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