2011-06-09 50 views
3

我寫了下面的代碼cin.gcount()及其應用

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

產量爲10預期....但後來我寫了下面的代碼

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

我進「你好「存儲在一個....這次的輸出是0而不是5 ...如果cin.gcount()返回最後一次輸入操作讀取的字節數,爲什麼這個差異

回答

4
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. 

來源:http://www.cplusplus.com/reference/iostream/istream/gcount/

std::cin格式化輸入。

2

我相信這是因爲gcount僅供格式化讀取。 operator>>是格式化的閱讀器,read不是。

3

其實cin.gcount()僅當get()方法函數getline()或閱讀()命令preceeded工作..... 所以它不會工作你想.... 參考的方式... http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html

+0

其他三個命令即得到()函數getline()讀取所有的輸入存儲在gcount的使用來獲取輸入的字符個數緩衝....... – 2011-06-09 12:21:52