#include "stdafx.h"
#include "string.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
FILE *fp1, *fp2;
char ime[32], prezime[32]; char brojbodova[5];
fp1 = fopen("ulaz.txt", "r");
char linija[100];
char linijacopy[100];
while(fgets(linija, sizeof(linija), fp1) != NULL)
{
/* or this: while (!feof(fp1))
{
fgets(linija, sizeof(linija), (FILE*)fp1);
rest of code*/
strcpy(linijacopy, linija);
strcpy(ime, strtok(linija , " "));
strcpy(prezime, strtok(NULL, " "));
strcpy(brojbodova, strtok(NULL, " "));
int bbodova = atoi(brojbodova);
if(bbodova <= 50)
{
printf("%s\n", linijacopy);
}
}
fclose(fp1);
return 0;
}
当我构建此解决方案时,我没有任何错误,但是当我运行此程序时,在打印结果后,我得到以下Windows错误:
控制台应用程序已停止工作。
Windows can check online for a solution to the problem. And there are three options: -Check online... -Close the program -Debug the program Problem details: Problem signature: Problem Event Name: APPCRASH Application Name: ConsoleApplication8.exe Application Version: 0.0.0.0 Application Timestamp: 5834b1c7 Fault Module Name: MSVCR110D.dll Fault Module Version: 11.0.50727.1 Fault Module Timestamp: 5011aa23 Exception Code: c0000005 Exception Offset: 0008f7b3 OS Version: 6.1.7601.2.1.0.256.1 Locale ID: 9242 Additional Information 1: 0a9e Additional Information 2: 0a9e372d3b4ad19135b953a78882e789 Additional Information 3: 0a9e Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
此程序在VS 2012中输入,操作系统是Windows 7 32 Enterprise。
答案 0 :(得分:0)
你的问题是假设每个函数都返回有效的指针,这是错误的
您必须检查fopen()
的返回值,否则您将取消引用NULL
指针。
您必须检查strtok()
的返回值,同样的问题→NULL
指针取消引用。
答案 1 :(得分:0)
以下代码解决了问题注释中列出的所有问题,并通过消除不需要的变量,代码逻辑等大大简化了代码。
//#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE_LEN (100)
int main( void )
{
FILE *fp1 = NULL;
char *brojbodova;
if( NULL == (fp1 = fopen("ulaz.txt", "r") ) )
{ // fopen failed
perror( "fopen for ulaz.txt failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
char linija[ MAX_LINE_LEN ];
char linijacopy[ MAX_LINE_LEN ];
while(fgets(linija, sizeof(linija), fp1))
{
strcpy(linijacopy, linija);
if( strtok(linija , " "))
{
if( strtok(NULL, " "))
{
if( NULL != (brojbodova = strtok(NULL, " ") ) )
{
int bbodova = atoi(brojbodova);
if(bbodova <= 50)
{
printf("%s\n", linijacopy);
}
}
else
{ // invalid line format
printf( "invalid line format, exiting: %s\n", linijacopy );
}
}
else
{ // invalid line format
printf( "invalid line format, exiting: %s\n", linijacopy );
}
}
else
{ // invalid line format
printf( "invalid line format, exiting: %s\n", linijacopy );
}
} // end while
fclose(fp1);
} // end function: main
以上代码在我的计算机上正常运行。
由于我在本地目录中没有名为:ulaz.txt的文件,因此它会输出相应的系统消息。
输出:
fopen for ulaz.txt failed: No such file or directory