c++ - getline() function is skipping inputs -


i have following code tests on nomc , nomp, using 2 successive getlines causes skipping the first 1 (getline(cin,nomp); ) .. how can fix problem ? ps : tried cin.ignore(); , cin.clear(); , didn't work

#include <iostream> #include<vector> #include<string> using namespace std;  int main() {     int t;     cin >> t;     vector<string> decision(t);     for(int i=0;i<t;i++)     {          string nomp,nomc;         string help="";         vector<string> desc;         bool accepted = true;         getline(cin,nomp);         getline(cin,nomc);         while(help!="----")         { getline(cin,help); desc.push_back(help);}         if ((nomp.size()<5)|| (nomp.size()>20))           {decision[i] = nomc+" rejected error code 1.\n";accepted=false;}         if (nomp[0]<65|| nomp[0]>90)             {decision[i] = nomc+" rejected error code 2.\n";accepted=false;}         if (nomp[nomp.size()]==32)             {decision[i] = nomc+" rejected error code 3.\n";accepted=false;}         if((nomc.size()<5)|| (nomc.size()>10))             {decision[i] = nomc+" rejected error code 4.\n";accepted=false;}         for(int j=0;j<nomc.size();j++)         {             if(((nomc[j]<48)&&(nomc[j]>57))||((nomc[j]<97)&&(nomc[j]>122)))             {decision[i] = nomc+" rejected error code 5.\n";accepted=false;break;}         }         if (desc.size()>10)             {decision[i] = nomc+" rejected error code 6.\n";accepted=false;}         for(int j=0;j<desc.size();j++)         {             if((desc[j].size()<1)||(desc[j].size()>80))             {decision[i] = nomc+" rejected error code 7.\n";accepted=false;break;}         }         if (accepted)             decision[i] = nomc+" ok.\n";     }     (int i=0;i<decision.size();i++)     {         cout<< decision[i] << endl;     } return 0; } 

look @ program way

int t; cin >> t; 

console input: 5\n

you may have noticed problem already. think 5, 5 + line break.

console input: name\n

then call getline()

cin buffer not: name\n,

it's actually: \nname\n

therefore, first getline reading single "\n"

and second one, reading "name\n"

there's ways approach issue. 1 doing trick

    while (isspace(cin.peek())) cin.ignore(); //dodge spaces, line breaks.      getline(cin, nomp);     getline(cin, nomc); 

i use windows, maybe line breaks \r\n in os, that's why doing single cin.ignore() may not enough. trick still works.

but there's better way: make function, returns when has read non empty line. like:

string my_getline() {     string result;      while (!getline(cin, result) || result.empty());      return result; }  string nomp = my_getline(); string nomc = my_getline(); 

with rvo fast doing getline(cin,nomp), , more simple.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -