C ++ control flow

int main()
{    
    char a[101];
    cout << "str a:";
    gets(a);
    return 0;
}

That's why gets(a);running up to cout<<"str a:";?

The compiler is used: digital mars and GNN_gcc.

+4
source share
3 answers

Buffers gets()and coutvarious. Since nothing makes the coutbuffer hide, the contents remain in the buffer when execution reaches the function gets(). To make the result fit your expectation and order of execution:

  • Option 1: use cout << "str a:" << endl;to force deletion of the contents of the buffer. You can also use flushif you do not need a new line.

  • 2: /, / . , , cin >> a; getline, cin.

, !

+1

gets(a); cout<<"str a:";?

gets() cout<<"str a:";, flush() , :

cout<<"str a:" << flush;

.

@Slava answer, std::cin.

, , flush().

gets() ( , ) C-, ,

std::ios::sync_with_stdio();

main() (. ).


:

gets(), ++ 14,

std::string a; // Much more convenient than char a[100];
std::getline(std::cin,a);
+8

(a); cout < "str a:";?

. , , cout , gets(). std::cout std::cin , . C- , std::cout , sync_with_stdio

+2

Source: https://habr.com/ru/post/1668441/


All Articles