2017-05-09 74 views
0

我有這些條目一個文本文件variables_n_paths.txt:如何使用字符串作爲C++ ifstream的變量名

nsf_ttj somepath1.txt 
nsf_zz  somepath2.txt 
hsf_ttw somepath3.txt 
hsf_wz  somepath4.txt 

我要的是這樣的事情(使用循環):

ifstream nsf_ttj(somepath1.c_str()); 
ifstream nsf_zz(somepath2.c_str()); 
ifstream hsf_ttw(somepath3.c_str()); 
ifstream hsf_wz(somepath4.c_str()); 

我做上面實現的是:

#include<iostream> 
#include<fstream> 
using namespace std; 

int main(){ 

    ifstream variable; 
    string path; 
    ifstream readfile("variables_n_paths.txt"); 
    while(true){ 
    if(readfile.eof()) break; 
    readfile >> variable >> path; //it gives error here 
    } 

    return 0; 
} 

這是我收到的錯誤:

error: ambiguous overload for ‘operator>>’ (operand types are ‘std::ifstream {aka std::basic_ifstream}’ and ‘std::ifstream {aka std::basic_ifstream}’)

我想知道,如果這甚至有可能。任何提示將不勝感激。提前致謝。

+0

您將'variable'聲明爲ifstream。你可能是想把它變成一個「串」。 – xslr

+0

是的,這是正確的。但即使我將它聲明爲一個字符串,如何將其轉換爲ifstream variablename? –

+1

你不能。變量名稱是編譯時結構。它們不能由運行時值確定。你爲什麼想這樣做?你認爲它會幫助你實現什麼? –

回答

0

您正在嘗試創建對象,它們的名稱基於輸入文件的內容。這對於純粹的C++來說是不可能的,因爲在編譯時必須知道對象名稱。

一種替代方法是在「變量名」和文件名作爲字符串來讀取,它們存儲在地圖並通過地圖迭代。

如果你絕對必須創建該文件的內容的變量名,您將需要爲使用解析文本文件,並生成包含正確的變量名對應的C++代碼的外部預處理器。

+0

非常感謝。我會嘗試,並將編輯帖子的答案。 –

0

是,能夠從一個(文件)流中提取的字符串。你的問題,因爲錯誤更專業術語解釋,就是variableifstream,你不能從一個流中提取的ifstream。只需將variable的類型更改爲std::string即可。

現在,你有一個字符串的文件名,你可以流的文件:

std::string variable, path; 
while(true) { 
    readfile >> variable >> path; 
    std::ifstream foo(path); 

然後你可以去和流文件的內容,並可能將其存儲在std::map使用variable作爲關鍵字 - 或者您想要對變量進行的任何操作。