c++ - Check function going into infinite loop and segmentation fault -


void inputstatisticaldata()  {     //variables declaration      cout << "\n[here take in data]" << endl;     //cin data      while (exit == false)     {         cout << "entered loop" << endl;//for troubleshooting purpose         cout << "countcheck: " << countcheck << endl;//for troubleshooting purpose          if (!vector.empty())         {             cout << "entered vector check if" << endl;//for troubleshooting purpose              if (condition)//checks if data has duplicates             {                 cout << "\ndata exist, please enter new set of data." << endl;                 break;             }              else             {                    cout << "entered countcheck++" << endl;//for troubleshooting purpose                 countcheck++;             }         }         else         {             //stores data             exit = true;         }     } } 

hi guys, above function take in data , store them object before storing vector. works fine, therefore decided validation checking function. 1 of check if data keyed in, been keyed in before.

i can store data once , that's it, once attempt store again, go infinite loop , give me segmentation fault. have been trying solve week no avail.

another infinite loop cin.fail. goes infinite loop if wrong input detected.

thanks taking time take look.

lol, why keep down-voting questions, there's question , solution, it's suppose others, stop down-voting , upvote it

you dealing infinite loop because error flags not reset @ end of iterations.

you should cin.clear() reset failbit before attempting other operations:

if(cin.fail()) {    cin.clear();    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input    ... } 

on second loop, check if vector of data empty or not. if not empty (a second entry) , data new, fall indefinitely in else statement increases countcheck.

two things may happen: infinite loop or segmentation fault (out of bounds exception).

you should check upperbound limit, e.g.:

if(countcheck > vector.size()) {     //this data new     ptd.setld(ld);     vector.push_back (ptd);     cout << "\nrecord stored successfully, returning main menu." << endl;     exit = true; } else if(vector[countcheck].getx() == mainx &&      ... } 

you use for statement instead:

for(countcheck = 0; countcheck  < vector.size(); countcheck ++) {     if(vector[countcheck].getx() == mainx && ...)     {         ...         exit = true;         break;     } }  //new element if(countercheck == vector.size()) {     ptd.setld(ld);     vector.push_back (ptd);     cout << "\nrecord stored successfully, returning main menu." << endl;     exit = true; } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -