Does the character '' (SPACE) count in the string in the C language?

0

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

#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();
}
    
asked by anonymous 15.01.2018 / 14:11

2 answers

1

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

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

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

In addition, fgets, just like scanf, adds a \x00 character, which represents the end of the string for most functions in C.

Instead of:

scanf("%s", nome);

Your line of reading would look like this:

fgets(nome, 20, stdin); 

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

    
15.01.2018 / 14:48
-1

scanf () caption, or reading , whenever you use % s it will pick up the character sequence until an empty space is added, which is represented by '\ 0' the end of its character string ("Null-terminated").

Then the string represents a sequence of characters. This is the simplest answer to consider.

A more complete answer at this link:

link

Reference: link

    
15.01.2018 / 14:27