2012-11-21 34 views
2

這是我的代碼。在C++中,打開帶有值的.txt文件後,讀取文件給我「」

ifstream readFile; 
readFile.open("voltages.txt"); 

if (readFile.fail()) 
{ 
    cout << "\nCould not open the file ... check to see if voltages.txt exists\n"; 
    system("pause"); 
    return; 
} 

string tempString = ""; 
//readFile.seekg(0, ios::beg); 
int idx = 0; 
if (readFile.is_open()) 
{ 
    while (readFile.good()) 
    { 
     getline(readFile,tempString); 
     cout << tempString << endl; 
    } 
    readFile.close(); 
} 

如果我移動voltages.txt到c:/,那麼它工作正常,但我有它在同一文件夾中的.exe我現在,當我設置一個斷點在COUT < < tempString endl; < < endl;它顯示爲「」。如果可能,我想保留在.exe中。正如你所看到的,我試圖尋求開始,沒有運氣。請幫助這個C++ noob!謝謝!

+0

多少行的時候voltages.txt是不是在C它讀:/? –

+0

它只讀一行,即「」 – KKendall

回答

2

這可能是因爲你試圖讀取本地文件時,程序需要從C到文件的鏈接:/

您可以測試這個用C:/pathToVoltages/voltages.txt

我建議傳球替換voltages.txt通過這樣的文件到您的可執行文件:

int main(int argc, char argv[]){ 
    ifstream readFile; 
    readFile.open(argv[2]); 
    /*Rest of the code*/ 

這是假設的路徑,該文件由你給程序作爲第一個參數給出:

./program pathToFile/voltages.txt 

希望這有助於