Search code examples
c++stringstdinbuffer-overflowistream

Prevent buffer overflow when using cin.getline and fgets in conjugation


The problem is that the size of strings is small. So the overflowing bits get assigned to next string.

I recently came to know that we shouldn't use fflush(stdin) for discarding unwanted sequence in input stream when using getline as it has undefined behaviour. People recommend to use cin.ignore() instead.

But what should we use for ignoring unwanted sequence in input stream with fgets?

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

int main() {
    string cpp;
    char c1[6];
    char c2[5];

    // Reading C++ string: GETLINE
    getline( cin, cpp);

    // Reading C string: CIN.GETLINE
    cin.getline( c1, sizeof(c1) );

    // cin.ignore(); DOESNT WORK
    // fflush(stdin); UNDEFINED BEHAVIOR


    // Reading C string: FGETS
    fgets( c2, sizeof(c2), stdin);

    cout << " " << cpp << '\n' << c1 << '\n' << c2 << '\n';

    return 0;
}

enter image description here


Solution

  • You can use the old fashioned c way to skip the rest of the line using getchar.

    char c;
    while((c = std::getchar()) != '\n' && c != EOF);