c - 为什么我的 C 代码会导致 Visual Studio 崩溃?

标签 c visual-studio-2013

我正在尝试用 C 语言编写代码来计算文本文件中的单词数(在本例中,文本文件有一个名称列表)。在它找到文本文件中的名称数量后,我想提示用户为每个名称输入一个分数(0 - 100 之间),然后计算平均分数。但是,每次我尝试运行我的程序时,它都会崩溃并弹出:

Visual Studio has crashed

这是我正在尝试编译的代码:

/*
1.  Read a list of names from a file called names.txt
2.  Count the number of names in the list.
3.  Prompt the user to provide a score (0 – 100) for each name in the file.
4.  Output the name and corresponding score to the file names_scores.txt
*/
#include <stdio.h>

#define IN 1//inside a word
#define OUT 0//outside a word

/*count lines, words, and characters in input*/
int main()
{
    int c;//storage variable for nw delimiters
    int nl;//new line
    int nw;//new word
    int nc;//next new character towards EOF 
    int nwCount;//number of words found in .txt file

    int state = OUT;//Indicates whether we're inside or outside of a word. We initialize
                    //it to being outside of the first word in the .txt file.

    nl = nw = nc = nwCount = 0;
    FILE *myFile = fopen_s("pfile", "names.txt", "r");
    if (myFile == NULL){
        perror("Error opening file.\n");
        return -1;
    }
    while ((c = _fgetchar()) != EOF){//let 'c' act as a storage variable for the nw delimiters

        ++nc;//increment the curent new character (do we need this incrementer?)
        if (c == ' ' || c == '\n' || c == '\t'){//nw delimiters
            state = OUT;
        }
        else {//if (state == OUT){
            state = IN;
            for (nwCount = 0; nwCount < 6; nwCount++){
                scanf_s("%d", &nw);
                nwCount += nw;
            }
        }   

    }//end of while loop

    //printf("%d %d %d\n", nl, nw, nc);//test the word counter

    int score = 0;
    int scoreQty = 0;
    int scoreSum = 0;
    int scoreAverage = 0;//scoreAverage = scoreSum / nwCount

    printf("There are ");
    printf("%d", nwCount);
    printf(" names in the names.txt file.\n");

    printf("Please enter a score integer (between 0 - 100) for each name.\n\n");
    for (scoreQty = 0; scoreQty < nwCount; scoreQty++){
        scanf_s("%d", &score);
        scoreSum += score;
    }

    printf("\nThe average score is: ");
    printf("%d %", scoreSum / scoreQty);
}

我使用 Visual Studio 2013 作为编译器。

最佳答案

崩溃原因是fopen_s调用错误。

改变

FILE *myFile = fopen_s("pfile", "names.txt", "r");

errno_t err;
FILE *myFile;
err = fopen_s(&myFile, "names.txt", "r");

参见fopen_s

关于c - 为什么我的 C 代码会导致 Visual Studio 崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878529/

相关文章:

c - 在 void 函数中操作结构

c - 两个大数相加只用C

uml - 如何在 Visual Studio 2013 中导出类图/UML?

c - 如何等待非子进程退出

c - 如何有效地阻塞线程直到满足特定条件

c++ - OpenSSL偶尔会打印随机垃圾

c# - 以编程方式单击 Windows 窗体应用程序中的网页按钮

unit-testing - 错误 C2338 : Test writer must define specialization of ToString<const Q& q> for your class

sql-server - VS2013 - SQL Server 单元测试 - 查询超时

c++ - 为什么我的析构函数仅在其父析构函数调用后才使我的代码崩溃?