我认为我的开关盒有问题

i think something's wrong with my switch case

本文关键字:有问题 开关 我的      更新时间:2023-10-16

我正在从一个txt文件中读取字符串,然后通过开关大小写将其与关键字列表(bubby、bonny、computer)匹配,然后初始化一个结构。但我得到了以下错误。

+        _struct    0x00efb7b0 {g=<Error reading characters of string.> HL=-431602080. mg_i=-431602080. ...}    D * 

#include <iostream>
#include <stdio.h>
#include <ctime>
#include <windows.h>
#include <fstream>
#include <string>
using namespace std;

struct D
{
    string g;
    float HL, mg_i, mg_m, t;
    float tau = HL / abs(log(0.5));
};


void scan(string, int&);

ifstream rlog;
ofstream wlog;
string line;
int main()
{
    int ptr;
    string month[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    //time_t t_i, t_f = time(0);
    //tm *ltm = localtime(&t_f);
    rlog.open("log.txt");
    scan(" :", ptr);

    string _list[3] = {"bubby", "bonny", "computer"};
    int j = 0;
    for (int i = 0; i < 2; i++){
        if (line.find(_list[i]) < line.length()){
            j++;
        }
    }
    D *_struct = (D*)malloc(j*sizeof(D));
    for (int i = 0; i < j; i++){
        if (line.find(_list[i]) < line.length()){
            switch (i){
            case '1':
                (_struct + i)->g = "bubby";
                _struct[i].HL = 9.0;
                _struct[i].mg_m = 150;
                break;
            case '2':
                (_struct + i)->g = "bonny";
                _struct[i].HL = 8.5;
                _struct[i].mg_m = 450;
                break;
            case '3':
                (_struct + i)->g = "computer";
                _struct[i].HL = 48.755;
                _struct[i].mg_m = 360;
                break;
            }
        }
    }

    return 0;
}

void scan(string s, int &i)
{
    while (!rlog.eof()){
        getline(rlog, line);        //READ IN
        if (line.find(s) > line.length()){}
        else{
            i = line.find(s);
            break;
        }                //EXIT FUNCT WEN FOUND
    }
}

提前感谢

您有一个严重的问题:

D *_struct = (D*)malloc(j*sizeof(D));

malloc函数只分配内存,不调用结构和类的构造函数,这意味着std::string成员D::g将无法正确构造。

在C++中,您几乎不应该直接使用malloc,当您想要动态分配内存时,您应该使用new,或者当分配数组new[]:

D* _struct = new D[j];

一个更好的解决方案是使用std::vector:

std::vector<D> _struct(j);

当然还有switch语句的问题,或者说它的情况。字符文字'1'实际上与ASCII编码中的整数49相同。此处不应使用字符文字,而应使用整数文字,因此请将例如'1'更改为1