Search code examples
carraysintscanf

How can I store a phone number input into a int array? C


I am creating a program which stores a name and a number from an input into a data structure. At the moment, I am trying to just make a simple function which gets the input (name and number) and inserts it into to two arrays. My input has to be in the format: name number. e.g

John 07745234574

which would then store the name in a character array and the number in a int array. The problem is it doesn't print the 0 at the beginning of the number, and adds a load of repeated numbers to then followed by numerous 0's when printed.

my code:

int main (void) {
char nme[20];
int nmbr[11];

printf("Enter:");
scanf("%s %d", nme, nmbr);

printf("\n%s ", nme);

int i;
for(i = 0; i<11; i++) {
    printf("%d", nmbr[i]);
    }
return 0;
}

I know that using %d wont work but I don't know another way of doing it without perhaps using a loop. Also, how would I store a number if it had a plus sign before it e.g +442962000292


Solution

  • char *nme;    
    int* nmbr;
    

    nme and nmbr are pointers and you should assign some memory before writing something to it.

    Read phone number also as a string.