Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin.gcount() and its applications

Tags:

c++

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

like image 701
AvinashK Avatar asked Oct 22 '25 15:10

AvinashK


1 Answers

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.

like image 138
Kiril Kirov Avatar answered Oct 25 '25 05:10

Kiril Kirov