2015-11-04 132 views
2

我試圖解析一個格式爲Key<whitespace>Value的文件。我正在讀取std::istringstream對象中的文件行,並從中提取Key字符串。我想要避免意外地更改Key字符串的值,使其爲const從「std :: istringstream」初始化「const std :: string」

我最好的嘗試是初始化一個臨時的VariableKey對象,然後使它成爲一個常量。

std::ifstream FileStream(FileLocation); 
std::string FileLine; 
while (std::getline(FileStream, FileLine)) 
{ 
    std::istringstream iss(FileLine); 
    std::string VariableKey; 
    iss >> VariableKey; 
    const std::string Key(std::move(VariableKey)); 

    // ... 
    // A very long and complex parsing algorithm 
    // which uses `Key` in a lot of places. 
    // ... 
} 

如何直接初始化一個常量Key字符串對象?

回答

3

將文件I/O從處理中分離出來,而不是在同一個函數中創建constKey可能更好 - 調用一個採用const std::string& key參數的行處理函數。

這就是說,如果你想繼續使用當前的模型,你可以簡單地使用:

const std::string& Key = VariableKey; 

沒有必要複製或移動任何地方任何東西。只有conststd::string成員功能可通過Key訪問。

2

可以通過提取輸入到一個函數避免「劃痕」變量:(綁定函數的結果到const引用延伸其壽命)

std::string get_string(std::istream& is) 
{ 
    std::string s; 
    is >> s; 
    return s; 
} 

// ... 

while (std::getline(FileStream, FileLine)) 
{ 
    std::istringstream iss(FileLine); 
    const std::string& Key = get_string(iss); 

// ... 

相關問題