In this main function, I get a segmentation fault whenever I enter "add //somenumber". If I use the other commands (remove, print, quit), the code works fine. I have the cout<<input right after getline is called to see the input. It will cout all the input options (including JUST "add") except when I input "add //somenumber". This is the code -
Code:
bool stop = false;
UnorderedList uList;
string input;
do {
try {
cout<<"Enter a command"<<endl;
getline(cin, input);
cout<<input;
if(strncmp(input.c_str(), "add", 3) == 0) {
cout<<"in add if";
int num;
if(input.size() <= 4 || input.at(3) != ' ' || input.at(4) == ' ')
throw UnorderedList::InvalidInputException();
else {
cout<<"in else";
num = atoi(input.substr(4, input.size()-4).c_str());
cout<<num;
uList.add(num);
}
} //end add
else if(strncmp(input.c_str(), "remove", 6) == 0) {
int num;
if(input.size() <= 7 || input.at(6) != ' ' || input.at(7) == ' ')
throw UnorderedList::InvalidInputException();
else {
num = atoi(input.substr(7, input.size()-7).c_str());
uList.remove(num);
}
} //end remove
else if(strncmp(input.c_str(), "print", 5) == 0)
cout<<uList.toString();
else if(strncmp(input.c_str(), "quit", 4) == 0)
stop = true;
else
throw UnorderedList::InvalidInputException();
}
catch(UnorderedList::EmptyListException &ex) {cout<<ex.what()<<endl;}
catch(UnorderedList::InvalidInputException &ex) {cout<<ex.what()<<endl;}
} while(!stop);
I don't see why I am getting a segmentation error. And what confuses me the most is that apparently the fault would occur at the getline call...since the cout<<input does not get called. Can someone tell me why this fault is happening? Thanks for any help.