The ' ' (SPACE) character, counts in the string in the C language?

Asked

Viewed 16,701 times

0

For example, it will only save the first letters before the space array, why ? Does anyone know how to explain ?

#include <stdio.h>

int main(void){     
    char nome[20];
    printf("Digite seu nome: ");    
    scanf("%s", nome);

    for(int c=0; c<20; c++{
        printf("%c", nome[c]);
    }
    getchar();
}

3 answers

2

In C, space is a normal character, like any other.

What you’re seeing as odd there, is that in fact the function scanf uses space as an input value separator by default.

If you instead of scanf use the function fgets, will have fewer surprises: all characters typed by the user will be transferred to the vector determined by you until a line break (string that depends on the operating system).

In addition, fgets, as well as scanf, adds a character \x00, that represents the end of the string for most functions in C.

Instead of:

scanf("%s", nome);

Your reading line would look like this:

fgets(nome, 20, stdin); 

and you wouldn’t be surprised by spaces, which would be a normal character. In addition, fgets can be used in real systems programs and libraries, which go into production, because it has the maximum string size to be read, and thus avoids buffer overflow problems. The scanf is a very versatile function for reading an arbitrary number of tokens, and even different data types, but it is more difficult to use correctly for simple cases.

-1

Use:

gets (nome);

That also works out

-1

  • So I was wanting to add ' 0' in hand and was not working kkk

  • I hope I’ve helped

  • The space in your array ' 20' , 'X20'

Browser other questions tagged

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