gpt4 book ai didi

c++ - 变量的值无法存储

转载 作者:行者123 更新时间:2023-12-03 07:11:38 25 4
gpt4 key购买 nike

编译器说这段代码没有错误,但是当我输入student total时,不会存储jlh的值,并且不会循环jlh次。我应该如何更改代码?

using std::string;

int main(){
int jlh,x,y;
string abs;

char **mhs=new char*[100];

cout<<"enter students total: ";
cin>>jlh;

for(x=0;x<jlh;x++){
cout<<"enter students name: ";
cin>>mhs[x];
cout<<"enter students presensi: ";
cin>>abs[x];
cout<<endl;
}


getch();
}

最佳答案

在阅读之前,您必须分配位置来存储阅读的内容:

#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;

int main(){
int jlh,x,y;
string abs;

char **mhs=new char*[100];

cout<<"enter students total: ";
cin>>jlh;

abs.resize(jlh); // allocate for presensi
for(x=0;x<jlh;x++){
cout<<"enter students name: ";
mhs[x] = new char[1024000]; // allocate for name, hoping this is enough...
cin>>mhs[x];
cout<<"enter students presensi: ";
cin>>abs[x];
cout<<endl;
}
}
使用 std::vectorstd::string代替原始数组应该更好:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;

int main(){
int jlh,x,y;

cout<<"enter students total: ";
cin>>jlh;

// allocate jlh elements for each vectors
std::vector<string> mhs(jlh);
std::vector<char> abs(jlh);

for(x=0;x<jlh;x++){
cout<<"enter students name: ";
cin>>mhs[x];
cout<<"enter students presensi: ";
cin>>abs[x];
cout<<endl;
}
}

关于c++ - 变量的值无法存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65042478/

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