【发布时间】:2016-04-07 17:37:18
【问题描述】:
首先,我决定在这里发布我的代码,以便每个人都能理解我在代码中遇到的问题,并能够更好地帮助我。
main.cpp
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include "validate.h"
#include "main.h"
using namespace std;
int main() {
name = getName();
score = quiz();
cout << "\n\n";
system("pause");
return (0);
}
string getName() {
cout << "Enter your name: ";
getline(cin, name);
val.set_item(name);
valid = val.vName();
if (valid) return name;
else {
cout << "Invalid name!\n\n";
getName();
}
}
int quiz() {
for (int loop = 0; loop <= 10; loop++) {
rand1 = rand() % 20 + 1;
rand2 = rand() % 20 + 1;
randop = rand() % 3;
op = operators[randop];
if (op == '*') ans = rand1 * rand2;
else if (op = '+') ans = rand1 + rand2;
else ans = rand1 - rand2;
cout << "What is " << rand1 << op << rand2 << " ? ";
getline(cin, input);
val.set_item(input);
valid = val.vInput();
if (valid) {
istringstream(input) >> inputint;
if (ans == inputint) {
cout << "Correct!\n\n";
score++;
}
else cout << "Incorrect!\n\n";
}
else cout << "Incorrect!\n\n";
}
return score;
}
验证.h
#ifndef validate_h
#define validate_h
using namespace std;
class validate {
string item;
int len;
bool check;
public:
void set_item(string x);
bool vInput() {
len = item.size();
for (int loop = 0; loop < len; loop++) {
if (item[loop] == '-' && loop == 0) continue;
check = isalnum(item[loop]);
if (check) continue;
else return false;
}
return true;
}
bool vName() {
len = item.size();
for (int loop = 0; loop < len; loop++) {
check = isalpha(item[loop]);
if (check) continue;
else return false;
}
return true;
}
};
void validate::set_item(string x) {
item = x;
}
#endif
main.h
#ifndef main_h
#define main_h
string name;
string input;
string getName();
validate val;
bool valid;
int quiz();
int score;
int rand1;
int rand2;
int randop;
int ans;
int inputint;
const char operators[3] = { '-', '+', '*' };
char op;
#endif
好的,所以我的代码编译得很好,并且完美地完成了所有事情。它询问名称,它知道何时无效,但这是我的第一个问题。当您输入错误的名称时,它会再次提示您输入。但是当你第二次进入它时它会崩溃。这是一个截图示例。
该程序也不会生成随机数。每次运行都一样。这是它的屏幕截图。
对于这些问题的任何帮助将不胜感激。
也适用于随机问题。我查看了其他问题,当我尝试修复“srand(time(NULL));”时它告诉我 srand 是模棱两可的。
【问题讨论】:
-
请限制自己每个问题回答一个问题。对于您的第一个问题,请提供minimal reproducible example,您至少应该通过使用调试器单步执行代码来找出代码崩溃的位置。您的第二个问题与以下内容重复:stackoverflow.com/questions/1108780/…
-
我尝试了其中的一些。随机的东西“srand (time(NULL));”告诉我 srand 模棱两可,所以我无能为力。
-
也可能是问题以某种方式联系在一起,所以我决定把它们都表达出来。
-
你这里有错误
else if (op = '+'),应该是== -
你为什么要把
getName函数写得这么奇怪(递归)?只需编写一个简单的while循环即可。
标签: c++ random crash duplicates