c++ - Why can I not use std::cin.getline() twice in succession? -


only first call getline() appears read in std::cin. fact buffer contains problem - why doesn't getline() overwrite contents of buffer?

how can second call getline() read in?

my code:

const int recordlen = 20;  // truncate input 20 chars void gettext(char line[]) {   std::cout << "enter gettext: ";   std::cin.getline(line, recordlen+1);   for(int = std::strlen(line); < recordlen; i++)   {     line[i] = ' ';   }   line[recordlen] = '\0'; }  int main() {   char buffer[340];   gettext(buffer);    std::cout << buffer;    std::cout << "now enter more text:";    // put more text buffer   std::cin.getline(buffer, 30);   std::cout << "you entered : " << buffer << std::endl;   return 0; } 

so - example output of program:

enter gettext: alskdjfalkjsdfljasldkfjlaksjdf alskdjfalkjsdfljasldnow enter more text:you entered :

after display of "now enter more text:", program displays "you entered:". not give me opportunity enter more text, neither display characters truncated previous call getline().

std::cin.getline(line, recordlen+1); 

here, if input longer recordlen chars, remaining characters not read , remain in stream. next time read cin, you'll read remaining characters. note that, in case, cin raise failbit, you're experiencing.

if first input recordlen chars long, newline remain in stream , next call getline appear read empty string.

other that, getline overwrite buffer.

if want ignore beyond first recordlen chars on same line, can call istream::clear clear failbit , istream::ignore ignore rest of line, after istream::getline:

std::cin.getline(line, recordlen+1); std::cin.clear(); std::cin.ignore( std::numeric_limits<streamsize>::max(), '\n' ); 

Comments