What is the difference between these string manipulations in C

Asked

Viewed 37 times

0

Good morning! I’m learning C and I had a question about using strings, I wanted to know if there is difference to use this form:

char palavra[255];

    printf("Digite uma palavra: ");
    
    setbuf(stdin, 0); //limpar o buffer
    fgets(palavra, 255, stdin); // ler a string
    palavra[strlen(palavra)-1] = '\0';

    printf("%s", palavra);

to use in this way:

printf("Digite uma palavra: ");
    scanf("%s", palavra);
    printf("%s\n", palavra);

From now on I thank you all!

1 answer

0


The second excerpt won’t read blanks.

Or rather, he will find that the blank space is the terminator of the scanf.

If later on in the program there is one more scanf, what comes after the previous white space will fill this new scanf.

That is, with each blank space, you leave a new string in the keyboard buffer.

  • Ah understood, but in practice I could use anyone who wouldn’t make an impact?

  • The second would have a certain impact, but only if you have one scanf subsequent and you do not enter the space bar.

  • I get it, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.