2014-11-25 40 views
0

我正在研究一個簡單的C++腳本,並希望在一個函數中打開一個文件的整個過程。但是,當我嘗試時,我的主要功能中出現錯誤。誰能幫我?這是我的代碼:如何從整個代碼的函數中打開一個文件?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 

using namespace std; 

string openFile(string fileName); 
int main(void) 
{ 
    string fileName; 
    cout << "Please input the file name (including the extension) for this code to read from." << endl; 
    cin >> fileName; 

    openFile(fileName); 

    fout << "File has been opened" << endl; 
    return 0; 
} 

string openFile(string fileName) 
{ 
    ifstream fin(fileName); 
    if (fin.good()) 
    { 
     ofstream fout("Output"); 
     cout << fixed << setprecision(1); 
     fout << fixed << setprecision(1); 
     //Set the output to console and file to be to two decimal places and 
     //not in scientific notation 
    } 
    else 
    { 
     exit(0); 
    } 
} 

回答

1
#include <iostream> 
    #include <fstream> 
    #include <string> 
    #include <iomanip> 

    using namespace std; 

    ofstream fout; 
    string openFile(string fileName); 
    void closeFile(); 

    int main(void) 
    { 
     string fileName; 
     cout << "Please input the file name (including the extension) for this code to read from." << endl; 
     cin >> fileName; 

     openFile(fileName); 
     if (fout.good()) //use fout in any way in this file by cheking .good() 
      cout << "File has been opened" << endl; 
     closeFile(); 
     return 0; 
    } 

    string openFile(string fileName) 
    { 
     cout << fixed << setprecision(1); 
     fout.open(fileName.c_str()); 
     if (fout.good()) { 
      fout << fixed << setprecision(1); 
      cout<<"Output file opened"; 
     } 
    } 
    void closeFile() 
    { 
     fout.close(); 
    } 
+0

謝謝你的代碼,但我希望能夠寫入文件以及從一讀。我如何修改這個可以做到這一點? – jjesh 2014-11-25 07:29:03

+0

你想寫入一個文件並從相同的文件或不同的文件讀取。 – Saravanan 2014-11-25 10:32:31

+0

我想要它,所以它從用戶輸入的文件中讀取,並輸出到一個名爲「Output.txt」 – jjesh 2014-11-27 03:51:00

0

你的代碼有很多很多的缺陷,

  1. fout << "File has been opened" << endl;,應該是,

    cout << "File has been opened" << endl;

  2. 不能再redifine相同varible。

    ofstream fout("Output");// first 
    cout << fixed << setprecision(1); 
    fout << fixed << setprecision(1); 
    //Set the output to console and file to be to two decimal places and 
    //not in scientific notation 
    ofstream fout("Tax Output.txt");//second 
    

在最後一行給一些其他的名字變量。

  • 你傳入std::string,在這裏應該通過const char *
  • ifstream fin(fileName);

    應該是,

    ifstream fin(fileName.c_str());