2010-11-18 17 views
0

包含ini文件: 地址=「localhost」的 用戶名=「根」 密碼=「你的密碼」 數據庫=「yourdatabasename」如何讀取「」與ifstream之間的單詞?

,我需要在兩者之間找到「」這個詞用ifstream的,並把它放在字符中。

有沒有辦法做到這一點?

+0

是在每個鍵之間有換行鍵=值? – Simone 2010-11-18 15:32:53

+0

是的,它們之間有行 – Marcus 2010-11-18 15:36:49

+0

我假設你的意思是'char *',而不是'char'。除非這是爲接口要求,否則幾乎肯定用'std: :string'。 – 2010-11-18 15:41:43

回答

0

如果在每對情侶之間有換行符,則可以執行以下操作。

std::string line; //string holding the result 
char charString[256]; // C-string 

while(getline(fs,line)){ //while there are lines, loop, fs is your ifstream 
    for(int i =0; i< line.length(); i++) { 
     if(line[i] != '"') continue; //seach until the first " is found 

     int index = 0; 
     for(int j= i+1; line[j] != '"'; j++) { 
      charString[index++] = line[j]; 
     } 
     charString[index] = '\0'; //c-string, must be null terminated 

     //do something with the result 
     std::cout << "Result : " << charString << std::endl; 

     break; // exit the for loop, next string 
    } 
} 
+0

Thx,但我不知道如何編程,你能幫忙嗎? – Marcus 2010-11-18 16:22:38

0

如下我想接近它:

  • 創建一個代表名稱 - 值對
  • 使用std::istream& operator>>(std::istream &, NameValuePair &);

然後你可以這樣做:

ifstream inifile(fileName); 
NameValuePair myPair; 
while(ifstream >> myPair) 
{ 
    myConfigMap.insert(myPair.asStdPair()); 
} 

如果你的ini文件包含部分,其中每個部分都包含命名 - 值對,那麼你需要閱讀到部分的結尾,以便你的邏輯不會使用流失敗,但會使用某種具有狀態機的抽象工廠。 (你讀了一些東西,然後確定它是什麼決定你的狀態)。

至於實施流讀入您的名稱 - 值對可以使用getline,使用報價作爲終止符。

std::istream& operator>>(std::istream& is, NameValuePair & nvPair) 
{ 
    std::string line; 
    if(std::getline(is, line, '\"')) 
    { 
    // we have token up to first quote. Strip off the = at the end plus any whitespace before it 
    std::string name = parseKey(line); 
    if(std::getline(is, line, '\"')) // read to the next quote. 
    { 
     // no need to parse line it will already be value unless you allow escape sequences 
     nvPair.name = name; 
     nvPair.value = line; 
    } 
    } 
    return is; 
} 

請注意,我沒有寫入nvPair.name,直到我們完全解析了令牌。如果流式傳輸失敗,我們不想部分寫入。

如果getline失敗,流將保持失敗狀態。這將在文件結束時自然發生。如果因爲這個原因而失敗,我們不希望拋出異常,因爲這是處理文件結束的錯誤方法。如果它在名稱和值之間失敗,或者如果名稱沒有尾部=符號(但不是空的),則可能拋出,因爲這不是自然發生的。

請注意,這允許引號之間的空格和換行符。無論他們之間是什麼,都被閱讀而不是另一個引號。你將不得不使用轉義序列來允許這些(並解析值)。

如果使用\」作爲轉義序列然後當你的價值,你必須‘循環’如果它與\結束(以及其更改爲報價),並一起將它們連接起來。