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

C++ Multiple Program Issues (rand, conversion, crashing)

本文关键字:转换 崩溃 rand 程序 问题 C++      更新时间:2023-10-16

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

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 << "nn";
    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!nn";
        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!nn";
                score++;
            }
            else cout << "Incorrect!nn";
        }
        else cout << "Incorrect!nn";
    }
    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是模糊的。

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

cin.ignore();

cin.clear();

以清除缓冲状态。我之前也遇到过类似的问题,我相信这就是解决方案。关于你的随机数,你还没有初始化随机种子。在使用生成随机数之前初始化随机种子

srand (time(NULL));

希望这能有所帮助。

编辑:

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

srand(time(0));

请确保在此解决方案的文件头执行#include <ctime>