1

I'm writing an fuction and I got a problem, the scanf function cant read spacebar " ", how can I solve it?

void add()
{
char choose2;   

FILE *fp;
struct booking book;    
system("cls");          
fp=fopen("hotelbooking.txt","a");
    if(fp == NULL)
    {   
        printf("There are no data file!");
    }
    else
    {
        printf("Add New Hotel Booking Record(s)\n");

        printf("  Name of Traveller: \n");  
        scanf("%s",book.travellername);
        fprintf(fp,"\n%s",book.travellername);

        printf("  Destination: ");  
        scanf("%s",book.destination);
        fprintf(fp,"\n%s",book.destination);                            
        fclose(fp);     
    }               
}

In the tervellername part, If I want to enter e.g. "Jason George", How can I scan the space bar between the name?

I'm using the structure below:

    struct booking
    {
    char travellername[20];
    char destination[20];
    }book;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Kin Hang Lee
  • 11
  • 1
  • 2

2 Answers2

3

scanf() with %s format specifier stops scanning as soon as it hits a whitespace. You cannot scan space using it.

Quoting C11, chapter §7.21.6.2,

s Matches a sequence of non-white-space characters.

For a better and robust alternative, you can use fgets() to scan an entire line, terminated by a newline. Remember, in this case, fgets() scans and stores the terminating newline also in the supplied buffer, so you need to manually get rid of it, if that matters.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Detail: "scanf() with %s format specifier stops scanning as soon as it hits a whitespace" --> With `"%s"` leading spaces do not stop scanning, they are consumed and not saved. It is spaces after non-white-space that stops scanning with `"%s"`. This is not directly observed with OP's example which has a middle space. Good suggestion about `fgets()`. – chux - Reinstate Monica Mar 08 '17 at 15:39
1

Try this

scanf("%[^\n]", book.travellername);

Input string will read space separated words and terminate upon encountering a newline character (i.e. \n). Also be Careful that this does not get buffer overflows. so define size of book.travellername accordingly.

update: I have updated the format specifier.

Community
  • 1
  • 1
roottraveller
  • 7,942
  • 7
  • 60
  • 65