1

I am trying to separate date/month/year from a string into multiple variables. When I try to print them I get unknown symbols.

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char string[40];
    char tempm[10], tempd[10], tempy[10];
    int month, date, year;
    int count = 0;
    printf("Introduceti data: \n");
    scanf(" %[^\n]s", string);
    for (int i = 0; i <strlen(string); i++){
      if (string[i] == '/'){
        count ++;
      }
      else{
        if (count == 0){
            strncat(tempm, &string[i], 1);
        }
        if (count == 1){
            strncat(tempd, &string[i],1);
        }
        if (count == 2){
            strncat(tempy, &string[i], 1);
        }
      }
    }
        printf("%s",tempm);
    }

And this is the output:

Introduceti data: 
11/12/21
Y��U11

How to delete 'Y��U'?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
FInch301
  • 21
  • 3

2 Answers2

1

Local variables are not initialised by default in C. You then need to explicitly provide a value for them before using it, like:

tempm[0] = '\0';

which will set tempm to the empty C-string. Or at the very same time of the definition:

char tempm[10] = "";
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

For starters these arrays

char tempm[10], tempd[10], tempy[10];

are not initialized and have indeterminate values. So they do not contain strings. But the function strncat supposes that the destination array contains a string. So calls like this

strncat(tempm, &string[i], 1);

result in undefined behavior.

You need to initialize the arrays like for example

char tempm[10] = "", tempd[10] = "", tempy[10] = "";

In fact there is no need to split a string into substrings. Instead you could use the standard C function strtol applied directly to the original string.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335