"Trash" values in arrays?

5

I've been practicing how to use vectors in c, and I've run into several simple programs that I've done with "junk" values, for example in the following code that consists of the user typing their full name, including spaces:

int main()
{
 int nombre,i=0;
 char s[20];
  printf("introdusca su nombre\n");
  while ((nombre = getchar()) != '\n')
   {
      s[i] = nombre;
      i++;
   }
  printf("%s\n", s);
}

when executing the program, if it manages to print the name including the spaces, but the problem is that many signs like these are added ╗┐ followed by the printed name, I do not know what the problem is, like when I use arrays but Instead of characters are numbers, something similar happens to me, but instead of ╗┐, I get extremely large numbers instead of the ones I type.

    
asked by esencia 09.08.2017 в 20:36
source

2 answers

5

In C the character strings are stored with termination by null character . This means that at the end of a string of characters a null character 'printf' is placed. This character acts as a marker that lets the chain treatment functions know that the end of the chain has been reached. printf is one of those functions.

With the code you have written, the characters that the user presses are stored until you press line break. But the null character terminator is never stored. That's why the %code% prints what the user has written followed by the garbage that was in the array.

The solution is to save the null character after the last saved character:

int main()
{
 int nombre,i=0;
 char s[20];
  printf("introdusca su nombre\n");
  while ((nombre = getchar()) != '\n')
   {
      s[i] = nombre;
      i++;
   }
  s[i] = '
int main()
{
 int nombre,i=0;
 char s[20];
  printf("introdusca su nombre\n");
  while ((nombre = getchar()) != '\n')
   {
      s[i] = nombre;
      i++;
   }
  s[i] = '%pre%'; // Marco el final de cadena con un caracter nulo
  printf("%s\n", s);
}
'; // Marco el final de cadena con un caracter nulo printf("%s\n", s); }

The previous code has a defect. If the user enters 20 or more characters before pressing the line break then we will write outside the array. This is a mistake but that would be a matter for another question.

    
answered by 09.08.2017 в 22:00
3

I managed to solve the problem, I had not initialized the vector, the only thing I did was instead of:

int s[20];

place:

int s[20]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

or:

int s[20];
while (s[19]!=0)
{
   s[j] = '
int s[20];
'; j++; }
    
answered by 09.08.2017 в 21:10