2015-09-03 64 views
1

保存在我的文件數據的std :: WS的角色(空格)是(空格都在開始時加入,並在最終的目的本次測試):讀取數據時

加載使用下面的代碼的數據有或沒有「std :: ws」不會導致任何區別。所以我對「std :: ws」的作用感到困惑,因爲我已經看到了使用它的代碼。有人可以解釋一下嗎?謝謝!

void main() 
{ 
ifstream inf; 
inf.open ("test.txt"); 

double x=0, y=0, z=0; 
string line; 

getline(inf, line); 
istringstream iss(line); 
//Using "std::ws" here does NOT cause any difference 
if (!(iss >> std::ws >> x >> y >> z >> std::ws)) 
{ 
    cout << "Format error in the line" << endl; 
} 
else 
{ 
    cout << x << y << z << endl; 
} 
iss.str(std::string()); 
iss.clear(); 

cin.get(); 

} 
+1

空白在默認情況下,提取開始除去。如果你有'std :: ios_base :: noskipws'或正在使用無格式輸入,那麼'std :: ws'可能會有用。 – 0x499602D2

+0

@ 0x499602D2該標誌被稱爲'skipws'; 'noskipws'是一個操縱器功能。 – Potatoswatter

+0

@ 0x499602D2:主要用途是沒有那麼多的時候'的std ::的ios_base :: skipws'被禁止,而是與格式化輸入不跳過前導空白。 –

回答

1

默認情況下,該流的skipws位設置和空白的每個輸入之前自動跳過。如果您使用iss >> std::noskipws取消設置,那麼稍後您需要iss >> std::ws

有些時候空白不會被自動跳過。例如,要檢測輸入的結尾,可以使用if ((iss >> std::ws).eof())

+0

謝謝!這非常有幫助! –

3

的主要用途的std::ws是格式和無格式輸入之間切換時:

  • 格式化輸入,即,使用在`>>值,跳過前導空白和停止每當格式填充通常的輸入操作符
  • 未格式化的輸入,例如,std::getline(in, value)確實跳過前導空白

例如,讀取時和fullname你可能會這樣來閱讀:

int   age(0); 
std::string fullname; 
if (std::cin >> age && std::getline(std::cin, fullname)) { // BEWARE: this is NOT a Good Idea! 
    std::cout << "age=" << age << " fullname='" << fullname << "'\n"; 
} 

但是,如果我進入使用

47 
Dietmar Kühl 

這個信息將打印像這樣

age=47 fullname='' 

問題是47後面的換行符仍然存在,並立即填寫std::getine()請求。因此,你想用這個語句來讀取數據

if (std::cin >> age && std::getline(std::cin >> std::ws, fullname)) { 
    ... 
} 

採用std::cin >> std::ws跳過空白,尤其是換行,並進行讀取輸入的實際內容在那裏。

+0

這看起來不像有效的輸入。字段應該用已知字符(新行或製表符)分隔,然後使用「忽略」轉到下一個字段。 – Potatoswatter

+0

@Patatoswatter:什麼是無效輸入?代碼和輸入原樣完全按預期工作。如果它讓你更舒服地假設'if()'條件被寫爲'if(std :: cout <<「輸入你的年齡:」&& std :: cin >> age && std :: cout <<「全名:「&& std :: getine(std :: cin >> std :: ws,fullname)){...}' –

+0

我的意思是,這是一個奇怪的程序,不關心輸入項是否出現在新行或不行。基本上你使用'>> ws'來確保換行符與製表符或空格相同。似乎對我懷疑。 – Potatoswatter

0

skipwsnoskipwsws不粘膩,所以如果你想跳過與WS空格,您必須在每次操作之前使用>>。

還要注意的是skipwsnoskipws僅適用於在流與運營商進行格式化輸入操作>>。 但ws適用於格式化輸入操作(使用操作符>>)和未格式化輸入操作(例如get,put,putback,...)。)

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main() 
{ 
    char c; 
    istringstream input("  1test  2test  "); 

    input >> skipws; 
    c = input.peek(); 
    //skipws doesn't skip whitespaces in unformatted input 
    cout << "After using skipws c = " << c << endl; 

    input >> ws; 
    c = input.peek(); 
    cout << "After using ws c = " << c << endl; 
} 

輸出:

After using skipws c = 
After using ws c = 1