c++ - 比较数组中的 2 个字符串时程序崩溃

标签 c++

我删掉了学生管理作业的这一部分,当我比较输入的 2 个名字,1,1 是我要搜索的内容时,它打印出结果但立即崩溃。请帮忙。感谢您的回复,谢谢

class Student
{
public:
    string name;
public:
    void input();
};
class list
{
private:
    Student ds[100];
    int count=0;
    int number,addnum=0;
    int total=number+addnum;
public:
    void input(int y);
    void find();
    friend class SinhVien;
};
void SinhVien::input()
{
    fflush(stdin);
    gotoXY(5,9);cout<<"name : ";
    cin>>name;
}
void list::input(int y)
{
    fflush(stdin);
    createBox(2,5,63,20,7);
    gotoXY(8,y-3);
    cout<<"add student\n";
    gotoXY(8,y-1);
    if (count==0)
    {
        cout<<"number of students : ";
        cin>>number;
        for(int i=1; i<=number; i++)
        {
            gotoXY(8,7);
            cout<<"student "<<i<<endl;
            ds[i].input();
            count++;
        }
    }
    else if(count>0)
    {
        cout<<"number of student : ";
        cin>>addnum;
        for(int i=1; i<=addnum; i++)
        {
            ds[i+count].input();
            count++;
        }
    }

}
void list::find()
{
    int count=0;
    string name1;
    gotoXY(10,51);
    cout<<"type name : ";
    cin>>name1;
    for(int i=0; i<total; i++)
    {
        string name2 =ds[i].name;
        if( name1.compare(name2) ==0)
        {
            cout<<"yes";
            count++;
        }
    }
    if(count==0)
        cout<<"not found";
}

int main()
{
    list a;
    a.input(1);
    int x;
    cin>>x;
    if (x==1)
        a.find();

}

最佳答案

int number,addnum=0;
int total=number+addnum;

您将total 初始化为number+addnum。但此时,number 还没有被赋值。所以分配给 total 的值是垃圾。当您使用它来停止循环时,您的循环可能会运行得太远并越界访问数组。

关于c++ - 比较数组中的 2 个字符串时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824814/

相关文章:

c++ - 在 C\C++ 中使用 XML 创建 GUI

c++ - 奇怪的执行

c++ - 在继承类型的指针之间进行静态转换

c++ - 这个char数组代码有什么问题?

c++指针的内存分配 vector

c++ - Filtergraph 在第一次数据通过后停止

c++ - VS2017 属性表排序

c++ - RotatedRect 与 Rect 或 RotatedRect OpenCV 的交集

c++ - 创建静态 CUDA 库以与 C++ 程序链接

c++ - 语句无法解析重载函数的地址