2013-12-10 52 views
0

我試圖打開一個.dat文件以用作我的程序的輸入。該任務說我需要將我輸入的文件名稱轉換爲c-string數據類型,以便通過.open(「」)命令讀取它。我的程序編譯完成,但我確信當我嘗試轉換文件名時,我做錯了什麼。我曾四處尋找有類似問題的人,但我沒有運氣,所以你可以給我的任何建議將非常感激!將文件的名稱轉換爲c字符串

這裏是我嘗試打開文件的功能,以及我嘗試轉換文件名的其他功能。

int main() 
{ 
    ifstream fp; 
    string name[SIZE], filename; 
    int counter, idx = 0; 
    float rate[SIZE], sum[SIZE], gross[SIZE], with[SIZE], pay[SIZE], net[SIZE], hours[SIZE]; 
    getfile(fp, filename); 
    readFile(fp, name, rate, hours); 
    pay[SIZE] = calcPay(rate, sum); 
    gross[SIZE] = calcGross(pay); 
    with[SIZE] = calcAmount(gross); 
    net[SIZE] = calcNet(gross, with); 
    output(name, rate, sum, with, gross, net, pay, SIZE); 
    return 0; 
} 

//Convert filename into C-string                  
string convert(ifstream &fp, string filename) 
{ 
    fp.open(filename.c_str()); 
    return filename; 
} 

//Get file name from user.                   
void getfile(ifstream &fp, string filename) 
{ 
    cout <<" Enter the name of the file: "; 
    cin>>filename; 
    convert(fp, filename); 
    fp.open("filename"); 
    if (!fp) 
    { 
     cout<<"Error opening file\n"; 
     exit (1); 
    } 
} 
+4

是什麼讓你覺得你做錯了什麼? – 0x499602D2

+0

當你運行程序時會發生什麼?如果編譯器沒有發出抱怨,您的轉換必須給出一些合理的結果... – abiessu

+0

當我輸入爲作業下載的.dat文件的名稱時,程序輸出「Error opening file」。 – user3063730

回答

1
cout <<" Enter the name of the file: "; 
cin>>filename; 
convert(fp, filename); 
fp.open("filename"); 

大概意思是(在本C++ 11支撐的情況下):

cout << " Enter the name of the file: "; 
cin >> filename; 
fp.open(filename); 

或(在C++ 03):

cout << " Enter the name of the file: "; 
cin >> filename; 
fp.open(filename.c_str()); 

備註:數組中的元素索引爲0SIZE - 1所以當你宣佈:

float pay[SIZE]; 

然後當你這樣做:

pay[SIZE] = calcPay(rate, sum); 

您正在訪問的內存 「通行證」 的最後一個元素,這將導致未定義行爲

+0

我正在建議c_str()我自己 – portforwardpodcast

+0

'fp.is_open()'不正確,因爲它不檢查失敗位。 'if(!fp)'是正確的習慣用語。另請參見:[basic_ios的參考資料](http://en.cppreference.com/w/cpp/io/basic_ios/operator!)。 – SoapBox

+0

@SoapBox:夠公平的,我不應該寫'if(!fp)'不正確。但是,如果文件不存在,'is_open()'可以做得很好。 – LihO