0

I was implementing stack in c code worked fine while using %s for inputting string without spaces, but failed when using %[^\n] to take strings containing spaces.

CODE:

/* Stack implementation */
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 5

typedef struct {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
} Book;

typedef Book dataType;


typedef struct {
    dataType arr[MAX_SIZE]; 
    int top;
} stack;

/* Function prototype */
Book input_book_details();
void initialize(stack *s);


/* main function */
int main(void) {
    stack s;

    initialize(&s);

    push(&s, input_book_details());
    push(&s, input_book_details());
    push(&s, input_book_details());

    return 0;

}

/*Function definitions */
Book input_book_details() {
    Book out_book;
    printf("Input Book Title: ");
    scanf("%[^\n]", out_book.title);
    //scanf("%s", out_book.title);
    fflush(stdin);
    
    printf("Enter Book Author Name: ");
    scanf("%[^\n]", out_book.author);
    //scanf("%s", out_book.author);
    fflush(stdin);
    
    printf("Enter Subject of Book: ");
    scanf("%[^\n]", out_book.subject);
    //scanf("%s", out_book.subject);
    fflush(stdin);
    
    printf("Enter Book ID: ");
    scanf("%d", &out_book.book_id);
    //fflush(stdin);

    printf("\n");

    return out_book;
}

void initialize(stack *s) {
    s->top = -1;
}

OUTPUT:

case 1: with %s for strings without spaces case1 case1.2

case 2: with %[^\n] for strings with spaces case2

Kunal Sharma
  • 416
  • 3
  • 12
  • 3
    Stick a space in front of it so `scanf(" %49[^\n]", out_book.title);` because `%[]` is one of the format specs that does not automatically filter whitespace. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). I added a length restriction too, to prevent buffer overflow or exploit. Note that `fflush(stdin);` is *undefined behaviour*. One reason, is it makes it impossible to redirect input from a file. – Weather Vane Jan 01 '22 at 16:19
  • 1
    `scanf("%[^\n]"` *doesn't* stop at a space, it may be failing for other reasons. The `%s` you previously used does stop at the first whitespace, but it also filters leading whitespace (unlike `%[]`). Always use the built-in ways of `scanf` to deal with whitespace, before resorting to a kludge. – Weather Vane Jan 01 '22 at 16:26
  • @WeatherVane problem still persist. :-/ – Kunal Sharma Jan 02 '22 at 18:32
  • There are three occurrences. – Weather Vane Jan 02 '22 at 18:34

0 Answers0