0

Here is a snippet of my code. The problem here is whenever I try to get a string input and put a white space in between (eg: name: John Michael), it skips the following scanf and proceeds to the third one which is the type. the skipping depends on how many white space I input (eg: 3 white spaces in name means, it skips three scanfs and prompts the fourth one)

why is this happening?

 int main (){
    char name, address, type[20], date, type1[20], type2[20];
    float previous, present, consumed_watts, bill;
    
    printf("Enter details below (PLEASE REFRAIN FROM USING SPACE, USE '_' INSTEAD!)");
    
    printf("\n\nEnter account name: ");
    scanf("%s", &name);
    printf("Enter address: ");
    scanf("%s", &address);
    printf("Enter type (residential or business): ");
    scanf("%s", &type[20]);
    printf("Enter previous reading: ");
    scanf("%f", &previous);
    printf("Enter present reading: ");
    scanf("%f", &present);
    printf("Enter date: ");
    scanf("%s", &date);
  • Your code invokes undefined behavior with literally *every* string read operation you're performing. – WhozCraig May 18 '22 at 10:49
  • 1
    That happens because `"%s"` reads till the next whitespace. Do you want to read a line? Use `fgets`. – mch May 18 '22 at 10:49
  • I've closed this as a duplicate to "how to use strings", but your problem is actually even more fundamental: how to use arrays. I always recommend to study arrays, then pointers, then strings, in that order. – Lundin May 18 '22 at 10:51
  • When using the `%s` format specifier, you require sufficient space for storing the input **including the terminating null character**. In the case of `name`, `address` and `date`, you are only passing a pointer to a single `char`, so you only have room for storing the null character, but no additional input. – Andreas Wenzel May 18 '22 at 10:52
  • Also, the `float` type is used by beginners often because they have old teaching materials. Get off on the right foot and use `double` as a matter of course, until you have a very good reason why you can't use `double`. – Weather Vane May 18 '22 at 10:54

0 Answers0