2017-03-01 120 views
0

考慮以下代碼:輸入流的std :: setfill和std :: setw?

int xx; 
std::cin >> std::setfill('0') >> std::setw(4) >> xx; 

當發送12標準輸入我期待的xx值是1200和發送12345時,我希望它是1234

但是,看起來std::setfillstd::setw沒有效果,我分別得到1212345

這是一個錯誤還是根據標準?有沒有一種很好的方法來獲得預期的功能?

另請注意,當我將xx的類型更改爲std::stringstd::setw生效,而std::setfill仍然不生效。

我的編譯器是gcc-7.0.1

+3

也許我錯過了。因爲什麼時候在* input *流操作上支持'std :: setfill'?我知道'std :: setw'是,但現在'std :: setfill'也是? – WhozCraig

+0

不行,這是惡意代碼。 –

+0

我不認爲輸入流支持'std :: setfill'。 http://en.cppreference.com/w/cpp/io/manip/setfill – Shravan40

回答

1

setwsetfill沒有如此普遍適用。

這聽起來像你想模仿固定寬度列中給定輸入格式的效果,然後重新讀取它。庫提供的工具確切地說:

int widen_as_field(int in, int width, char fill) { 
    std::stringstream field; 
    field << std::setw(width) << std::setfill(fill); 
    field << std::setiosflags(std::ios::left); 
    field << in; 
    int ret; 
    field >> ret; 
    return ret; 
} 

Demo

不過,該功能不會削減123451234。這將需要通過string進行另一次轉換。

1

根據C標準,setfill屬於輸出流。至於setw,它與char*string一起使用時適用於輸入流。例如,下面的程序(1234561234)輸出abcd用於輸入字符串abcdef

string a; 
cin >> setw(4) >> a; 
cout << a; 
相關問題