0

I'm very new to C. I'm trying to figure out how to print out an user input that is made of chars including spaces. For example "-- John Smith --" should print out "-- John Smith --".

The following code works when the string has no spaces, but otherwise nothing happens. I did read that the scanf function does not read spaces, and we should use the fgets functions instead, but I can't seem to get it to work.

#include <stdio.h>

char *str[];

void main() {

    print_string();   

}


void print_string() {

    scanf("%s", &str);
    printf("%s", str);

}

maliebina
  • 205
  • 6
  • The code posted does not compile without warnings or errors. There is no real substitute for working through a good text book chapter by chapter. If you do have a text book, get a newer one, because `void main()` is now deprecated. It should be `int main(void)` – Weather Vane Oct 09 '22 at 12:04

1 Answers1

0

I'd suggest having a look at the following question: How do you allow spaces to be entered using scanf.

I also had issues compiling your code, so I made some changes.

  #include <stdio.h>
   // Simply created a fixed size array
   char str[50];
   // Need to declare function since we are using it before
   // its implementation
   void print_string();
   
   // main needs to return int
   int main() {
     print_string();
     // return 0 on success
     return 0;
   }
  
  void print_string() {
      // since the array above was set to 50, it is best to declare
      // an input of 49 characters to avoid buffer overflow. 
      // Use 49 characters, so that scanf can insert the terminating character 
      scanf("%49s", str);
      printf("%s", str);
  }