[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.