0
void reg() {
    char name[60];
    char city[1000];
    puts("Name");
    scanf("%s", name);
    puts("City?");
    scanf("%s", city);
    FILE *fptr = fopen("./src/details.txt", "a");
    fputs(strncat(strncat(name, " ", 61), city, 1061), fptr);
    fclose(fptr);
}

When I call this function (present in another file) from main, it doesn't execute (program runs without any output). In fact, any function with scanf in my file doesn't execute. However, functions without scanf work fine. Could anyone tell me what's wrong?

Archer
  • 271
  • 5
  • 15

2 Answers2

1

To wait for a user input after printing the text, you must use fflush(stdout) to clear buffer.

Rather than:

puts("Name");
scanf("%s", name);

Do:

puts("Name");
fflush(stdout); // this
scanf("%s", name);
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • `puts` flush the output thanks to the newline produced at the end – bruno May 30 '20 at 16:54
  • 2
    `name` is a char array and hence it already refers to the base address of the array so the ampersand is not needed. – Amal K May 30 '20 at 16:56
  • @AmalK is right, remove the `&` and change the comment to be `// don't forget to NOT put an ampersand here` ^^ – bruno May 30 '20 at 16:57
  • if something must be done this is to add the max length to read, and to test the return value, so `if (scanf("%59s", name) != 1) { ...error...}` – bruno May 30 '20 at 16:59
0

Try substituting scanf() with fgets() to read strings.

fgets(name, 60, stdin);

Also your error with scanf() most probably seems to be caused by a trailing whitespace that is left unconsumed. Add:

scanf(" %*c");

Or add a call to getchar() before calling scanf()

Amal K
  • 4,359
  • 2
  • 22
  • 44