0

So I have a list of names and corresponding phone numbers, and I want the user to be able to continuously enter a new name-number pair into that list. The part of my code where I try to do that looks something like this:

char name[20], list_names[1000][20], phone[20], list_phone[1000][20];
int n;

n = 0;
do
{
   printf("Enter name: ");
   scanf("%20[^\n]", name);

   printf("Enter phone number of %s: ", name);
   scanf("%20[^\n]", phone);

   strcpy(list_names[n], name);
   strcpy(list_phone[n], phone);

   n += 1;
}
while (n < 1000);

This usually gives me an error like "incompatible pointer type". I have to do it the indirect way and first store the name in a separate variable. But how do I get the string from that variable into the list? Probably there's something I don't get in the strcpy() part. Thanks for helping out!

  • Unfortunately I can't scan it directly into the list. In the complete code I need to check some things first of the entry before I add it to the list. So I need to be able to add the string from the variable into the list. – MrStrategschi Apr 20 '20 at 09:32
  • `name[20]` -> `name[21]` because you need one more char for the NUL terminator. But there may be more problems. – Jabberwocky Apr 20 '20 at 09:39
  • I tried "fgets" but it caused the same problems. – MrStrategschi Apr 20 '20 at 09:49
  • 1
    I think you should [edit] your question and show us a [mcve] including the verbatim error messages you get as well as the verbatim input and output – Jabberwocky Apr 20 '20 at 09:55

1 Answers1

1

try this

        printf("Enter name: ");
        scanf(" %19[^\n]", name);//add one space and turn 20 to 19 (leave space for '\0')

        printf("Enter phone number of %s: ", name);
        scanf(" %19[^\n]", phone);
hanie
  • 1,863
  • 3
  • 9
  • 19