我正在尝试用C编写代码来计算文本文件中的单词(在这种情况下,文本文件有一个名称列表)。在找到文本文件中的名称数量后,我想提示用户为每个名称输入一个分数(0到100之间),然后计算平均分数。但是,每次我尝试运行它的程序时,它都会崩溃并弹出:
以下是我正在尝试编译的代码:
/*
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作为编译器。
答案 0 :(得分:1)
崩溃的原因是fopen_s
的呼叫不正确。
更改
FILE *myFile = fopen_s("pfile", "names.txt", "r");
到
errno_t err;
FILE *myFile;
err = fopen_s(&myFile, "names.txt", "r");
请参阅fopen_s