【问题标题】:How to open a file with a user inputted variable in C?如何在 C 中使用用户输入的变量打开文件?
【发布时间】:2014-03-10 21:40:39
【问题描述】:

我正在编写一个 POS 程序作为学校作业。我正在使用多个 txt 文件作为数据库。该程序假设允许用户输入 SKU 编号(例如 123),然后它将在数据库中打开一个 txt 文件(例如 database/123.txt)。然后它从 txt 文件中提取信息,例如价格,并允许用户添加多个文件并以总计结束。用户还可以通过创建新的 SKU 添加到数据库中。他们还能够查看交易历史。我遇到的问题是我似乎无法弄清楚如何记录用户的号码,然后使用该号码打开以该号码开头的文本文件。 (例如使用输入 123 然后打开 123.txt。)

这是我需要帮助的代码部分:

// 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; 
    }
}

【问题讨论】:

    标签: c database text input io


    【解决方案1】:
    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
    

    那么你可以用sprintf组成一个完整的文件名,例如

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

    请注意,上述内容不会执行错误检查或溢出保护 - 您可能需要考虑添加一些。

    【讨论】:

    • scanf(3) 不打印任何东西,应该是printf(3)... 并且需要一个体面的格式,等等。
    • @vonbrand:确实——一个语句中有这么多错误,我只注意到两个!
    【解决方案2】:

    您需要将用户输入与您的数据库路径和扩展名连接起来。

    查看此帖子:C string append

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多