0

I am getting and displaying names, and stop the program when I type enter key. At the below code I get the correctly result (I know "gets" is deprecated):

#include <stdio.h>

main()
{
    char name[50];

    while(1)
    {
        printf("Name: ");
        scanf("%s", name);

        if(name[0]=='\0')
            break;
        else
            printf("Name entered: %s\n", name);
    }
}

But when I try to use scanf:

printf("Nome: ");
scanf("%s", nome);

The condition name[0]=='\0' never is true this time. Why? The '\0' works differently in these functions?

Ricardo
  • 67
  • 8

2 Answers2

1

If scanf cannot assign a value to a variable (because the input stream has a whitespace, terminating the 'string'), it doesn't clear it out; the reason is partly that not all variables have an obvious 'clear' state.

So after your scanf, the nome still contains whatever it contained before. You need to check if scanf was able to assign a variable instead, by testing its return value: if (scanf(...) == 1) - which means 'did scanf successfully assign one variable?'

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • If I put some names I can display this name, it means that scanf worked. But when I type enter (no characters) then the program doesn't end. So I guess the '\0' is not in the array "name". Is that? – Ricardo Jul 04 '16 at 14:35
  • Yes, the '\n' tells scanf to _stop reading_, and it doesn't copy it in the name, it _stops_. – Aganju Jul 04 '16 at 16:21
  • Sorry guys, "nome" means "name". In the first code `scanf("%s", name);` actually is `gets(name);`. – Ricardo Jul 04 '16 at 20:15
-1

Using "scanf" the variable doesn't become a string but with "gets" the variable (name) becomes string because "gets" automatically puts '\0' in it?

Ricardo
  • 67
  • 8