我正在为玩《龙与地下城》制作一个应用程序,只是为了娱乐,我遇到了一个问题。我写了多个printfs,但不知何故它停止了工作。当它完成第一个计算并且必须继续进行下一个计算时,它将停止。我不知道为什么。
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <string>
int main(){
//variables
int dmgDice;
char entityName, dmgType;
int initiative, dmgBonus, damage, userAC, userHp;
//user input
printf("Type in your armor class: \n");
scanf("%d", &userAC);
printf("Type in your hit points : \n");
scanf("%d", &userHp);
printf("type in your initative: \n");
scanf("%d", &initiative);
printf("type in you damage bonus: \n");
scanf("%d", &dmgBonus);
printf("type in you damage type: \n");
scanf("%s", &dmgType);
printf("your damage dice: \n");
scanf("%d", &dmgDice);
printf("Entity you want to damage: \n");
scanf("%s", &entityName);
//d20 roll
srand((unsigned)time(0));
printf("d20 roll: \n");
int d20roll = (rand() % 20);
int SUM = d20roll + initiative;
printf("you have rolled SUM %d + %d = %d", d20roll, initiative, SUM);
if(d20roll > 14){
printf("\nYou've passed the enemies AC, now roll for damage!");
printf("\nYou did %d damage to the %s!", damage, entityName);
}
else{
printf("\nYou have missed, now %s attacks..", entityName);
int entityd20roll = (rand() % 20) + 1;
printf("\n%s passed your armor class, now it will roll for damage");
if(entityd20roll > userAC){
int edmg = (rand() % 12);
int hp = userHp - edmg;
if(hp < 0)
hp *= -1;
printf("\nhit points taken: \n");
printf("%s has dealt %d damge", entityName, edmg);
}
else{
printf("%s has missed you", entityName);
}
}
return 0;
}
此外,如何创建一个内存文件,使用户不必一遍又一遍地键入所有内容?
答案 0 :(得分:1)
我建议包括该库,并使用cout<<
和cin>>
尝试相同的操作,因为这些命令的工作方式略有不同。
例如printf("Type in your armor class: \n");
成为cout<<"Type in your armor class: "<<endl;
然后scanf("%d", &userAC);
变成cin>>userAC;
对于文件保存系统,建议您遵循文件I / O上的课程,例如以下视频:https://www.youtube.com/watch?v=Iho2EdJgusQ。 然后,您可以将用户的所有选项写入文件,然后在程序启动时读取信息。这样,用户的首选项将得以保留。
答案 1 :(得分:0)
我建议(如@ samu_242已经完成的那样)使用std::cout
和std::cin
命令作为输入。
在您的代码中,printf
printf("\n%s passed your armor class, now it will roll for damage");
期望一个字符串(%s),但是您什么也没传递。此外,也许您曾想过要使用字符数组,但是您只为一个字符分配了内存:
char entityName, dmgType;
通过这种方式,entityName
将仅获得用户在输入中输入的第一个字符(例如,如果他/她键入“地精”,则entityName
将仅具有“ G”)。要声明char
的数组,请使用
char entityName[N];
其中N是数组的最大长度。也有动态分配内存的方法,但我的建议是使用std :: string。