我认为我的开关盒有问题
i think something's wrong with my switch case
我正在从一个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
。
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 我在范围内未声明的错误类有问题
- 我的C++语言蛮力算法有问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++类中的友元函数有问题?
- 我对数组即 0x6dfe78 有问题
- 我对 std::unique(算法)C++有问题
- 使用 fstream 库并在屏幕上打印的文件有问题?
- 这个模板为什么有问题?如何正确编译
- 我对 MyGraph 属性顶点名称和边权重有问题
- delete[]有问题,如何部分删除内存
- 在C++中使用exit()退出程序有问题吗
- 跳转到if(false)块有问题吗
- 查找有问题的宏
- 使用 rand() 和 srand() 有问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 我在 C++ "out_of_range at memory location"有问题
- 在循环中与开关语句有问题
- 我认为我的开关盒有问题