c++ array of objects, failed initialization -
this question has answer here:
- cin , getline skipping input [duplicate] 4 answers
need project school using arrays of class objects. can't use vectors, answers suggesting them not help. ive been trying create such , array, put name in each object. ive tried running loop this, , keeps skipping first object in array. help?
#include <iostream> #include <cstring> using namespace std; class car { private: char* driver; public: void setdriver(char* name) { driver = name; } void getdriver() { cout<<driver; } }; int main() { int numdrivers; cout<<"how many drivers like?"; cin>>numdrivers; car* roster = new car[numdrivers]; for(int i=0;i<numdrivers;i++) { char* name; name = new char[20]; cout<<"name:"; cin.getline(name, 20); roster[i].setdriver(name); } for(int i=0;i<numdrivers;i++) { roster[i].getdriver(); cout<<".\n"; } return 0; }
ive toyed ranges of loops, still same thing when hits loop set names drivers. looks this
how many drivers like?: 4 name:name: name1 name: name2 name: name3 . name1. name2. name3.
any appreciated.
per comment, same problem answered in cin , getline skipping input
the exact way affects code follows. execute these lines read number 4 (for example) input:
cout<<"how many drivers like?"; cin>>numdrivers;
the >>
operator reads enough characters cin
determine there number 4 there (and number ends @ 4). not read farther, else might have typed on line still there. if hit "return" key after "4" thing remaining on line newline character ends line, it's still there anyway.
the next interaction user during input loop when i
0
. code executes:
cout<<"name:"; cin.getline(name, 20);
so program prints "name" console , waits until there input terminated newline character. there input waiting read (left on cin>>numdrivers
). program reads in carriage return nothing before it. processes empty string , goes on second iteration of loop.
Comments
Post a Comment