首页 > 解决方案 > 无法存储变量的值

问题描述

编译器说这段代码没有错误,但是当我输入学生总数时,它不会存储 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();
  }

标签: c++

解决方案


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

#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::vectorandstd::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;
    }
}

推荐阅读