arrays - C++ cin gets skipped, even after I use cin.ignore() -


just make clear, new c++. wrote small program test skill arrays , ran problem cin.

if user enters number, like program expects them to, well. if string gets entered, input skipped , program ends.

i set of inputs this: cin >> x;cin.clear();cin.ignore();

so awry??

here full code:

#include <iostream> #include <cstdlib> using namespace std;  int main() {     system("cls");     int create = 1;     int entry;     int x;     string chc;     cout << "how long should array be?" << endl;     cout << ":";     cin >> x;cin.clear();cin.ignore();     if(x<1){x=1;}     int myarray[x];     string askcontinue;     for(int x=0;x<sizeof(myarray)/sizeof(myarray[0]);x++){         system("cls");         cout << "enter value #" << x+1 << endl;         cout << ":";         cin >> entry;cin.clear();cin.ignore();         myarray[x]=entry;     }     system("cls");     cout << "index - value" << endl;     for(int x=0;x<sizeof(myarray)/sizeof(myarray[0]);x++){         cout << x << " ------ " << myarray[x] <<endl;     }     system("cls");     cout << "restart? [y/n]" << endl;     cout << ":";     cin >> chc;cin.clear();cin.ignore();     if(chc=="y" || chc=="y"){main();} } 

cin >> x;cin.clear();cin.ignore(); 

this thing you're doing throughout program part of problem. if user enters doesn't meet formatting requirements integer, stream goes failure state. directly after happens clear stream , discard next character. if user entered in more 1 character part of invalid input, ignore() call discarding next character, not all of invalid input.

you need check if input did not succeed, , discard input using overload of ignore() takes number of characters wish discard. following if wish consistently ask user input if not provide valid characters:

while (!(std::cin >> x)) {     std::cout << "how long should array be?" << std::endl;     std::cin.clear();     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } 

but judging code, doesn't want repeatedly ask user input. in case, should check valid input instead , nothing in invalid case:

if (std::cin >> x) {     ... } 

also, vlas (or variable-length arrays) non-standard feature of c++, provided extentions in compilers. don't use them. instead, allocate dynamically using std::vector:

std::vector<int> myarray(x); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -