digito_evo
digito_evo

Reputation: 3672

Duplicate input issue caused by `std::ios_base::sync_with_stdio( false );`

When I use std::ios_base::sync_with_stdio( false ); in the below, the program asks for the first input twice while it should ask once.

#include <iostream>
#include <array>
#include <limits>


int main( )
{
    // std::ios_base::sync_with_stdio( false ); // uncommenting this line cause
                                                // the said problem

    std::array<char, 168> buffer1 { };
    std::array<char, 168> buffer2 { };

    std::cin.putback( '\n' );
    std::cin.clear( );
    std::cin.ignore( std::numeric_limits<std::streamsize>::max( ), '\n' );
    std::cin.getline( buffer1.data( ), 168 );

    std::cin.putback( '\n' );
    std::cin.clear( );
    std::cin.ignore( std::numeric_limits<std::streamsize>::max( ), '\n' );
    std::cin.getline( buffer2.data( ), 168 );

    std::cout << "\nbuffer1:\n" << buffer1.data( ) << '\n';
    std::cout << "buffer2:\n" << buffer2.data( ) << '\n';
    std::cout << "\nEnd" << '\n';

    return 0;
}

I want the code to ask for input twice, once for buffer1 and once for buffer2 but this happens:

32581 // as can be seen, here I enter a random character sequence for buffer 1 but it doesn't store it in buffer1 and asks for input again
12345 // Instead, this sequence gets stored in buffer1
abcde // buffer2 has no problem, this gets stored in buffer2 successfully

buffer1:
12345
buffer2:
abcde

End

However, avoiding the use of std::ios_base::sync_with_stdio( false ); fixes this bug:

32581
abcde

buffer1:
32581
buffer2:
abcde

End

How should I fix this bug? Why is it happening?

Upvotes: 0

Views: 87

Answers (1)

Nimrod
Nimrod

Reputation: 3543

The problem here is the first putback(\n') fails when you call

std::ios_base::sync_with_stdio( false );

So the call ignore is blocking until you type in something.

In your case, the first line you type in "32581" is ignored.

A solution maybe just remove the first put to ignore part. I dont think its necessary here.

Upvotes: 1

Related Questions