gpt4 book ai didi

C++ 多程序问题(rand、转换、崩溃)

转载 作者:行者123 更新时间:2023-12-01 19:42:55 25 4
gpt4 key购买 nike

首先,我决定在这里发布我的代码,以便每个人都可以理解我在代码中遇到的问题,并能够更好地帮助我。

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

好的,我的代码编译得很好并且完美地完成了所有事情。它询问名称,它知道它何时无效,但这是我的第一个问题。当您输入错误的名称时,它会再次提示您输入。但是第二次输入的时候就崩溃了。这是一个屏幕截图示例。

crash issue

该程序也不生成随机数。每次运行都一样。这是一个屏幕截图。

duplicating numbers

对于这些问题的任何帮助,我们将不胜感激。

也针对随机问题。我查找了其他问题,当我尝试修复“srand(time(NULL));”时它告诉我 srand 是不明确的。

最佳答案

关于当您调用 getName() 时您的应用程序崩溃的问题,尝试刷新 cin缓冲区使用:

cin.ignore();

cin.clear();

清除缓冲区状态。不久前我遇到了类似的问题,我相信这就是解决方案。关于您的随机数,您尚未初始化随机种子。在生成随机数之前初始化随机种子:

srand (time(NULL));

希望这有帮助。

编辑:

刚刚看到你上面的评论。尝试使用以下内容代替您的随机数种子:

srand(time(0));

确保你这样做#include <ctime>位于此解决方案的文件头部。

关于C++ 多程序问题(rand、转换、崩溃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36483421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com