Reputation: 21
the compiler says this code has no error but when i enter students total, the value of jlh it isn't stored and it won't loop jlh times. how should i change the code?
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();
}
Upvotes: 1
Views: 71
Reputation: 75062
You must allocate place to store what are read before reading things:
#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;
}
}
Using std::vector
and std::string
instead of raw arrays should be better:
#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;
}
}
Upvotes: 3