在文件中存储分数:程序在c中运行时崩溃

时间:2014-12-29 11:33:17

标签: c

我想使用C创建一个文本文件,每次运行代码时都会继续添加分数而不删除最后一条记录。不幸的是,当我运行代码时,它所做的只是运行printf语句并创建一个文件score.txt,但不会写入任何内容,而只是崩溃。

以下是代码:

int main()    
{
    FILE *score;
    score = fopen("score.txt", "w");
    fclose(score);
    int s;
    char n;
    printf("You got a high score!\nPlease enter score: ");
    scanf("%d", &s);
    printf("\nPlease enter your name: ");
    scanf("%s", &n);
    fprintf(score,"%d", s);
    fprintf(score,"%d", n);
    printf("\nData Stored into score.txt\n");
    return 0;
}

3 个答案:

答案 0 :(得分:4)

这里有多个问题。

  1. fclose(score);之后,您尝试使用fprintf(score,"%d", s);。为什么?也许您想在fclose(score);;

  2. 之前移动return 0
  3. 始终对fopen()的返回值进行成功检查。另外,根据您的要求,keep on adding score every time the code is run without deleting the last record您需要{em>追加模式中的fopen()。详细了解模式及其使用情况here

  4. scanf("%s", &n);错了。这里你想要的是一个数组,而不是一个char。考虑将char n;更改为char n[32];或其他内容。 [注意:一旦n为数组,请将scanf()更改为scanf("%s", n);]

  5. fprintf(score,"%d", n);错了。不要使用不兼容的格式说明符。对于字符串,它应该是%s [即使在您的情况下,n也是char。格式说明符不应该是%d。]

答案 1 :(得分:2)

上面给出的代码几乎没有问题。

  • 如果您需要添加新分数而不删除旧分数,则需要以追加模式打开文件。
  • 在进行fclose之前,您必须将分数写入文件。
  • char n只能容纳一个char。如果你打算用更多字符读取一个正确的名字,你需要一个char数组,比如char name [100]。

下面给出的代码提供了一种附加到文件的正确方法。

    FILE *score;
    char name[100];
    int nScore;

// Open the file
    score = fopen("score.txt", "a+");
    if(!score)
    {
        printf("Failed to open");
        return 1;
    }

// Get user inputs
    printf("You got a high score!\nPlease enter score: ");
    scanf("%d", &nScore);
    printf("\nPlease enter your name: ");
    scanf("%s", name);

//Write to file
    fprintf(score, "Name: %s  Score: %d\n", name, nScore);

// Close the file
    fclose(score);
    printf("\nData Stored into score.txt\n");

    return 0;

答案 2 :(得分:0)

另请注意,名称n无法存储为char。它必须是char []char *。这可能是造成你崩溃的原因,虽然@SouravGhosh也是正确的 - 基本上你的代码中至少有两个错误。

E.g。

char n[80]; // or any other reasonable value, or learn dynamic memory allocation
scanf("%s", n);