【发布时间】:2022-01-15 04:38:34
【问题描述】:
当我在下面使用std::ios_base::sync_with_stdio( false ); 时,程序会询问第一个输入两次,而它应该询问一次。
#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;
}
我希望代码要求输入两次,一次用于buffer1,一次用于buffer2,但这会发生:
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
但是,避免使用std::ios_base::sync_with_stdio( false ); 修复了这个错误:
32581
abcde
buffer1:
32581
buffer2:
abcde
End
我应该如何修复这个错误?为什么会这样?
【问题讨论】:
-
你在用什么
OS?我无法重现您的问题。 -
@WBuck Windows 10 和命令提示符。
-
@WBuck 我已经在 Command Prompt 和 PowerShell 上对其进行了测试。
-
是否有任何必要的理由将其设置为 false?