drhorseman
drhorseman

Reputation: 23

unable to write sentence after space in c programming

#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

Upvotes: 1

Views: 39

Answers (1)

Vincent
Vincent

Reputation: 166

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?

Upvotes: 1

Related Questions