Barbiyong
Barbiyong

Reputation: 147

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.

Upvotes: 1

Views: 27856

Answers (4)

Sahil Sareen
Sahil Sareen

Reputation: 1834

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

Upvotes: 0

niko
niko

Reputation: 9393

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

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

Upvotes: 4

awesum
awesum

Reputation: 35

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

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

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.

Upvotes: 0

Related Questions