2013-07-16 38 views
0

我有這樣的情況下,我需要得到一個文件中每行兩個int值與此格式:fstream的一個字符串分隔符或兩個char

43=>113 
344=>22 

是否有可能做些事情,如設置一個分隔符等於=>而不是使用>>運算符分配整數?

ifstream iFile("input.in"); 
int a,b; 
iFile >> a >> b; 

還可以自動完成以類似的格式輸出嗎?

oFile << a << b; 

代替

oFile << a << "=>" << b; 

感謝。

+1

一個小班似乎是你最簡單的賭注。 – chris

回答

0

如果您始終有=>作爲定界符,您可以編寫一個函數來解析文檔的行。

void Parse(ifstream& i) 
{ 
    string l; 
    while(getline(i,l)) 
    { 
     //First part 
     string first = l.substr(0, l.find("=>")); 

     //Second part 
     string second = l.substr(l.find("=>")+2, l.length()); 

     //Do whatever you want to do with them. 
    } 
} 
1

鑑於ab是內置類型的變量,你無法定義自己的用戶定義運算的流他們(標準庫中已經提供了這樣的功能)。

你可以只寫出來與你想要的行爲的代碼...

int a, b; 
char eq, gt; 

// this is probably good enough, though it would accept e.g. "29 = > 37" too. 
// disable whitespace skipping with <iomanip>'s std::noskipws if you care.... 
if (iFile >> a >> eq >> gt >> b && eq == '=' && gt == '>') 
    ... 

OR包裝abclassstruct,並提供用戶自定義的運營商所提供。有很多SO問題的答案解釋瞭如何編寫這樣的流媒體功能。

寫支持功能...

#include <iomanip> 

std::istream& skip_eq_gt(std::istream& is) 
{ 
    char eq, gt; 

    // save current state of skipws... 
    bool skipping = is.flags() & std::ios_base::skipws; 

    // putting noskipws between eq and gt means whatever the skipws state 
    // has been will still be honoured while seeking the first character - 'eq' 

    is >> eq >> std::noskipws >> gt; 

    // restore the earlier skipws setting... 
    if (skipping) 
     is.flags(is.flags() | std::ios_base::skipws); 

    // earlier ">>" operations may have set fail and/or eof, but check extra reasons to do so 
    if (eq != '=' || gt != '>') 
     is.setstate(std::ios_base::failbit) 

    return is; 
} 

...然後用它像這樣...

if (std::cin >> a >> skip_eq_gt >> b) 
    ...use a and b... 

此功能 「作品」,因爲流的目的是接受「io操縱器」函數重新配置流的某個方面(例如,std::noskipws),但對於要調用的函數,只需匹配(輸入)io操縱器的原型:std::istream& (std::istream&)

+0

這並不奏效,因爲它會接受'42 => 3'這樣的東西。 (如果可能正確,接受第一個空格;接受第二個空格可能不正確。) –

+0

糟糕。我注意到你在評論中提到了這一點。一種可能性是「if(iFile >> a >> eq && iFile.get(gt)&& iFile >> b && eq =='='&& gt =='>')'。就個人而言,我更喜歡操縱器。 –

+0

我明白了。是否可以在不使用變量的情況下使用操作符>>?比如:'iFile >> a >> >> >> b;'? – codiac

1

讀或寫 時,你不能直接這樣做,沒有任何額外的代碼,但你可以寫一個處理它 你更明確地操縱:

std::istream& 
mysep(std::istream& source) 
{ 
    source >> std::ws;  // Skip whitespace. 
    if (source.get() != '=' || source.get() != '>') { 
     // We didn't find the separator, so it's an error 
     source.setstate(std::ios_base::failbit); 
    } 
    return source; 
} 

然後,如果你寫的:

ifile >> a >> mysep >> b; 

,你會得到一個錯誤是分隔符是缺席的。

在輸出時,您可以使用類似的機械手:

std::ostream& 
mysep(std::ostream& dest) 
{ 
    dest << "=>"; 
    return dest; 
} 

這有保存的信息,以什麼 分離器在這兩個特殊功能(這 將被定義的下一個孤立的優勢彼此,在同一個源文件中), 而不是散佈在任何你正在閱讀或寫作的地方。

此外,這些數據可能代表您的代碼中某些特定類型的 信息。如果是這樣,那麼您應該將其定義爲一個類,然後定義運算符>><<,並將該類定義爲該類的 類。

相關問題