有人可以帮我理解我的代码有什么问题。一切顺利,直到p指针为分配的内存带来一个字母而不是一个数字。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int key;
int c = 0;
int number;
int coins;
int coins2;
char answear;
int n;
int* p;
FILE* fp;
fp = fopen("D://coins.txt", "r");
PAR2: coins = 100;
if (!fp) // daca fp nu exista;
{
printf("No previous data!.\n");
}
if (!feof(fp)) // the condition to be read line by line from the txt file.
{
printf("Taking values:\n");
fscanf(fp, "%d", & c); //reading values from the savegame.
coins = c; //getting coins from the savegame.
}
fclose(fp);
for (n = 1; n > 0;) //infinite loop
{
if (coins <= 0) //if running out of coins
{
PAR4: printf("Sorry but you have no dollars left. Try again Y/N?\n");
PAR3: answear = getch();
switch (answear) //testing answear
{
case 'Y':
{
goto PAR2; //give 100
}
case 'y':
{
goto PAR2; //give 100
}
case 'N':
{
exit(1);
}
case 'n':
{
exit(1);
}
default: //if the answear if undifined
{
printf("Not an option. Answear only with Y/N!\n");
goto PAR3;
}
}
}
PAR1: printf("You have: %d$\n", coins);
printf("\nEnter your number! WARNING: it must be between 1 and 5 only.\n");
p = (int*)malloc(sizeof(int)); //memory for number variable
scanf("%d", p); //take the number
if (*p > 0 && *p < 6) //I need the number to be between 1 and 5
{
printf("Your number is: %d\n", number);
showing the chosen number
key = (rand() % 5) + 1; //generating a random key
printf("The extracted number is: %d\n", key);
if (key == number)
if the key is guessed {
printf("Congratulations! You have won 10$.\n");
coins2 = coins + 10;
} else {
printf("You are not so lucky this time!\n");
coins2 = coins - 10;
}
coins = coins2;
printf("Rotate again? Y/N!\n");
play again ?
PAR5 : answear = getch();
switch (answear) //test the answear
{
case 'Y':
{
system("cls"); //clear screen
goto PAR4; //going to the starting of the loop
}
case 'y':
{
system("cls");
clear screen
goto PAR4; //going to the starting of the loop
}
case 'N':
{
fp = fopen("D://coins.txt", "w");
save the coins
fprintf(fp, "%d", coins);
fclose(fp);
exit(1);
}
case 'n':
{
fp = fopen("D://coins.txt", "w"); //save the coins
fprintf(fp, "%d", coins);
fclose(fp);
exit(1);
}
default:
{
printf("Not an option. Answear only with Y/N!\n");
goto PAR5;
}
}
} else
printf("Wrong number:\n");
/*
Message if a letter or symbol has been entered (this message is shown over and over again, and I don't know why...)
even if it's infinite loop, the loop it should reset so it should again pass the statements above, but it doesn't.
*/
free(p); // free the number.
}
getch();
return 0;
}
答案 0 :(得分:1)
您无法通过测试feof(fp)
来检查是否可以从文件中读取数据。您必须尝试阅读并检查阅读API的返回值:getchar()
将在文件末尾返回EOF
,fgets()
将返回NULL
。 scanf()
将返回EOF
。 feof()
函数只能在文件结尾被读取操作后使用。
除此之外,你的代码不会编译,它最好是伪代码,最糟糕的是基本的意大利面代码。
不要以这种方式使用标签和结构,使用循环和测试对代码进行编码,并将其中的一部分拆分为单独的函数。