Please give me coding advice to add hyphen for C language phone number

Asked 6 days ago, Updated 6 days ago, 1 views

#include <stdio.h>

typedef struct people{
  char name[100];
  int num;
  char phone[16];
}People;

void phone_number(char m[], int n){
  char phone_a[16];
  int i;
  for(i = 0; i <= 3; i++){
    phone_a[i] = m[i];
    if(i == 3)
      phone_a[3] = n;
  }

  for(i = 4; i <= 8; i++){
    phone_a[i] = m[i-1];
    if(i == 8)
      phone_a[8] = n;
  }

  for(i = 9; i<=12; i++){
    phone_a[i] = m[i-2];
  }

  for(i = 0; i <= 16; i++){
    m[i] = phone_a[i];
  }
}

int main(){

  People student;

  scanf("%d %s %s", &student.num, student.name, student.phone);

  phone_number(student.phone, '-');

  printf("%d\n", student.num);
  printf("%s\n", student.name);
  printf("%s\n", student.phone);

  return 0;
}

void phone_number(charm[, int) function to add hyphen(-), so I coded it in the same way as above, but the runtime error appeared.

How do I make this code shorter?

  20211234 Honggil-dong 01012345678
20211234 
Hong Gil-dong 
010-1234-5678

c

2022-09-20 13:31

1 Answers

It's a null-terminated string, but after copying each character to phone_a, the last null is not added, so the garbage value is attached.

There can be many modifications.

When declaring the phone_a region variable as shown below, I think the problem will be solved by filling it with null in advance.

char phone_a[16] = {0, };


2022-09-20 13:31

If you have any answers or tips


© 2022 pinfo. All rights reserved.