0

I'm writing a POS program as a school assignment. I'm using multiple txt files as a database. The program is suppose to allow the user to enter a SKU number (e.g. 123) then it will open a txt file in a database (e.g. database/123.txt). It then pull info from the txt file such as a price and allow the user to add multiple files and end with a total. The user can also add to the database by creating new SKUs. They are also able to view transaction history. The issue I am having is I can't seem to figure out how to record a number from a user and then use that number to open a text file beginning with that number. (e.g. use enters 123 then 123.txt is opened.)

Here is the section of my code that I need help with:

// Function to start a transaction
int transaction(void)
{
    // Define Variables
    char buf[1000], nDatabase[100];
    float nPrice[500], nTotal;

    // Instructions
    printf("You have started a transaction.\n");
    printf("Enter the SKU number below.\n");
    printf("Enter 0 to complete the transaction.\n");


    // Begin loop here
    do
    {
        FILE *ptr_file;

        // record SKU number
        /*remove test tools later*/
        printf("we r here\n");
        scanf("Enter the SKU: %c\n", &nDatabase);
        printf("now we r here\n");


        // Open database file  
        /*Change location later*/
        ptr_file = fopen("database/123.txt", "r");
        // If file is not found return 1
        if (!ptr_file)
        {
            printf("Could not match that SKU number.\n");
            return 1;
        }


        while (fgets(buf, 1000, ptr_file) != NULL)
            printf("%s\n", buf);
        scanf("%s", &nPrice[0]);
        // Close file
            fclose(ptr_file);

            while (nDatabase == 0); 
                nTotal = nPrice[0] + nPrice[1];
                printf("Your total is: $%.2f\n", &nTotal);
                return 0; 
    }
}
Clifford
  • 88,407
  • 13
  • 85
  • 165

2 Answers2

2
printf( "Enter the SKU: " ) ;  // <-- scanf if only for input, the prompt must be output separately
scanf( "%s\n", nDatabase);
//       ^     ^
//       |     |_No & here - nDatabase is an array
//       |
//       |_Accept a string not a character

Then you might form a complete file name with sprintf, e.g.

char filename[MAX_FNAME] ;
sprintf( filename, "database/%s,txt", nDatabase ) ;

Be aware that no error checking or overrun protection is performed by the above - you may want to consider adding some.

Clifford
  • 88,407
  • 13
  • 85
  • 165
0

You need to concatenate the user input with you database path, and extension.

Check this post: C string append

Community
  • 1
  • 1