-1

So I am working on a class assignment and I have the basic program down but I am trying to go above and beyond the assignment. I have load from a predefined .dat file but I want to also give the user the option to define their own .dat file so here is my code so far:

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

int main()
{
    //Loads Variables
    FILE *inputFile;
    char *firstName[15];
    char *lastName[15];
    char choice[15];
    printf("Welcome Friend File Importer\n");
    printf("What is the name of the file you want imported:\n");
    scanf("%s",&choice);
    printf("you entered %c\n",choice);
    if (choice == NULL)
    {   
        printf("Friends.dat Loaded By Default\n");
        choice = "friends.dat";
    }
    inputFile = fopen(choice, "r");  //Loads Input File
    //If there is an issue then let the user know
    if (inputFile == NULL)
    {
        printf("You got some issues... check to make sure the file exists.\n\n");
        system("pause");
        return -1;
    }
    //Starts to print out the friends list
    printf("\nYour friends\n\n");
    fscanf(inputFile, "%s%s", firstName, lastName);
    while (!feof(inputFile))
    {
        printf("%s %s\n", firstName, lastName);
        fscanf(inputFile, "%s%s", firstName, lastName);
    }
    fclose(inputFile);
    system("pause");
    return 0;
}

So I am wondering if the issue is because I am using scanf or is because I am trying to assign a variable inside of an if statement. Please talk to me like I am five I have dyslexia and learn better by doing then by reading.

jxh
  • 69,070
  • 8
  • 110
  • 193

3 Answers3

1

You can't assign to an array, you have to copy to it. In your case you should use strcpy.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You have to use strcpy when you want to copy a string to another.

That is:

choice = "friends.dat";

has to change to

strcpy(choice ,"friends.dat");

And to print a string, you should use %s format specifier:

printf("you entered %s\n",choice);

instead of

printf("you entered %c\n",choice);
Mansuro
  • 4,558
  • 4
  • 36
  • 76
1

choice is an array. You cannot assign to an array.

An array will never compare equal to NULL, since an array name in an expression will decay to the address of its first element.

To detect if no suitable input for choice was provided, it is easier to read the entire line first with fgets(), and then parse the line using sscanf(). Both scanf() and sscanf() return the number arguments were saved. So if scanf("%s", choice) returns 1, it means it succeeded in storing a string in choice. Otherwise, you can assume a failure occurred.

jxh
  • 69,070
  • 8
  • 110
  • 193