Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

c++ - Why does in_avail() output zero even if the stream has some char?

#include <iostream>
int main( )
{
   using namespace std;
   cout << cin.rdbuf()->in_avail() << endl;
   cin.putback(1);
   cin.putback(1);
   cout << cin.rdbuf()->in_avail() << endl;
   return 0;
} //compile by g++-4.8.1

I think this will output 0 and 2

but when I run the code, it output 0 and 0, why?

or if I change cin.putback(1); to int a; cin >> a; with input 12 12;

it still outputs 0 and 0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Apparently it's a bug/feature of some compiler implementations Insert the line

cin.sync_with_stdio(false);

somewhere near the beginning of code, and that should fix it

EDIT: Also remember that in_avail will always return 1 more than the number of chars in the input because it counts the end of input character.

EDIT2: Also as I just checked, putback does not work unless you have attempted to read something from the stream first, hence the "back" in "putback". If you want to insert characters into the cin, this thread will provide the answer: Injecting string to 'cin'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...