This code is not running properly as it keeps returning 0xC0000005 on codeblocks and on CMD nothing happens. I checked online and it says I should initialize the vector before I write to it but how can I initialize a vector of objects if I don't know how many objects the user is gonna enter(as it should be increasing the more inputs the user uses).
#include <string>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
class stock {
private:
    int sharenumber;
    float shareprice;
    string sharename;
public:
    stock(int x, string y,float z)
    :sharenumber(x),sharename(y),shareprice(z)
    {
        cout<<"An object has been created";
    }
    string getstring(){
        return sharename;
    }
};
int toint(char * x){
   int y;
   y = atoi(x);
   return y;
}
string tostring(char * x){
   stringstream ss;
   string z;
    ss<<x;
    z = ss.str();
   return z;
}
float tofloat(char * x){
   float u;
   u = atof(x);
   return u;
}
int main(int argc, char *argv[])
{
    char str1[]= "buy";
   vector <stock*> P_obj;
 if (strcmp(str1,argv[1]) == 0){
    cout<<"this ran"<<endl;
   P_obj.push_back(new stock(toint(argv[2]),tostring(argv[3]),tofloat(argv[4])));
    cout<<P_obj[0]->getstring();
}
return 0;
}
You should check the number of input before using the input. The argc argument will indicate how many inputs are given as the command line argument (including the first argument, which is typically the name of the executable file).
int main(int argc, char *argv[])
{
    char str1[]= "buy";
    vector <stock*> P_obj;
    if (argc > 1){ // check the number of input
        if (strcmp(str1,argv[1]) == 0){
            cout<<"this ran"<<endl;
            if (argc > 4) { // check the number of input
                P_obj.push_back(new stock(toint(argv[2]),tostring(argv[3]),tofloat(argv[4])));
                cout<<P_obj[0]->getstring();
            } else {
                cout<<"too few arguments for "<<str1<<endl;
            }
        }
    } else {
        cout<<"no command"<<endl;
    }
    return 0;
}
 MikeCAT
 MikeCATUser contributions licensed under CC BY-SA 3.0