我有這些條目一個文本文件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}’)
我想知道,如果這甚至有可能。任何提示將不勝感激。提前致謝。
您將'variable'聲明爲ifstream。你可能是想把它變成一個「串」。 – xslr
是的,這是正確的。但即使我將它聲明爲一個字符串,如何將其轉換爲ifstream variablename? –
你不能。變量名稱是編譯時結構。它們不能由運行時值確定。你爲什麼想這樣做?你認爲它會幫助你實現什麼? –