开发者

cin.gcount() and its applications

I wrote the following code

#include< iostream>  
using namespace std;  
int main()  
{  
 char a[30];  
 cin.read(a,10);  
 cout<<(cin.gcount());  
  system("pause");  
  return 0;     
}  

the output was 10 as expected....but then i wrote the following code

#include< iostream>    
using namespace std;   
int main()    
{    
 char a[30];    
 cin>>a;   
 cout<<(cin.gcount());    
  system("pause");    
  return 0;       
}   

I entered "hello" which got stored in a.... the output this time was 0 instead 开发者_开发问答of 5...if cin.gcount() returns the number of bytes read in last input operation, why this difference


Returns the number of characters extracted by the last unformatted input 
operation performed on the object.

The unformatted input operations that modify the value returned by 
this function are those performed by the following member functions: 
get, getline, ignore, peek, read, readsome, putback and unget.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Notice though, that peek, putback and unget do not extract characters. 
So gcount will always return zero after a call to any of these.

Source: http://www.cplusplus.com/reference/iostream/istream/gcount/

std::cin is not unformatted input.


I believe this is because gcount is only for unformatted reads. The operator>> is a formatted reader, read is not.


Actually the cin.gcount() only works if preceeded by get() getline() or read() command..... so it wont work the way you are trying to.... for reference... http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜