c++ - 无法存储变量的值
问题描述
编译器说这段代码没有错误,但是当我输入学生总数时,它不会存储 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::vector
andstd::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;
}
}
推荐阅读
- sql - SQL > 服务器 > 如何查询附加字段
- python - 根据动态的、类似 ARRAY 的列值过滤掉数据
- html - HTML:将表格右对齐放置在其他表格单元格中
- python - GRU 层的经常性 dropout 大大增加了损失值
- c++ - 树莓派接线Pi c++调用对象作为中断
- r - A + B 与 NA 在 r
- c++ - 带定时器的 C++ 线程状态机
- perl - Mojolicious Lite 插件“Log::Any”丢失
- shell - 用于 mariadb 的 Vagrant VM shell 脚本自动化以在关机触发器上备份数据库
- angular - 我如何对子组件进行角度路由