1
#include<stdio.h>

struct books {
  char author[100];
  char title[100];
  char publisher[100];
  int pubyear;
  int pages;
  float price;
}
bookObject[10];

void swap(int array1, int array2) {
  int temp = array1;
  array1 = array2;
  array2 = temp;
}

void swapC(char * array1, char * array2) {
  char temp = * array1;
  * array1 = * array2;
  * array2 = temp;
}
void swapF(float array1, float array2) {
  float temp = array1;
  array1 = array2;
  array2 = temp;
}

void Display(int n) {
  int i;
  for (i = 0; i < n; i++) {
    printf("\n");
    printf("Book title : ");
    printf( bookObject[i].title);
    printf("Author name : ");
    printf("%s\n", bookObject[i].author);
    printf("Publisher name : ");
    printf("%s\n", bookObject[i].publisher);
    printf("Publishing year : ");
    printf("%d\n", bookObject[i].pubyear);
    printf("No of pages : ");
    printf("%d\n", bookObject[i].pages);
    printf("Price : ");
    printf("%.2f\n", bookObject[i].price);
    printf("\n");
  }
}

This is a C program , the problem is that when i try to add multiple names in a single place the program gets disturb like for ex. if i put the book title as: python it will work correctly but i put name as intro to python the program starts to behave abnormally same goes to author name. i'm attaching the screenshot for further referance

enter image description here

but works well for single word enter image description here

drhorseman
  • 23
  • 6
  • `%s` stops reading at any white space. Suggest using `fgets` instead to read each line of input. Be aware that `fgets` stores the trailing newline into the buffer so you'll have to remove that if you don't want that stored. – kaylum Dec 06 '20 at 21:40
  • could you please write one statement of this program using fgets? – drhorseman Dec 06 '20 at 21:42
  • If you still need further help (and for all future questions), please provide a [minimal verifiable example](https://stackoverflow.com/help/minimal-reproducible-example). 90% of the code shown is not relevant to the actual problem. An MVE is the smallest amount of complete code needed to repro the problem. – kaylum Dec 06 '20 at 21:43
  • i have edited my code now is it ok? – drhorseman Dec 06 '20 at 21:45
  • Ah, not really because the code is not complete (it can't be compiled exactly as shown) and it doesn't even contain the problem code anymore as there is no code that reads the input now. Anyway, it'll be something like: `fgets(bookObject[i].title, sizeof(bookObject[i].title), stdin)` – kaylum Dec 06 '20 at 21:47

1 Answers1

1

Use fgets({var}, {max_buffersize}, stdin) instead of scanf() if you don't know the amount of spaces the user will enter.
If you're really intent in using spaces, you need to use a format specifier, which will read until a '\n' character is met. scanf("%[^\n]", {var}) would work in your case.

Reference: How do you allow spaces to be entered using scanf?

Vincent
  • 156
  • 5