2015-05-29 16 views
0

我正在試圖使一個函數獲取兩個參數一個Line_number和第二個字符串。這個函數將打開一個預先填充的文件,並跳過直到達到「Line_number」行,獲取該行,然後發佈其他行,但它不起作用。我看到了其他解決方案,但無法找到正確的解決方案。請幫助我。轉到行號,並在文件中使用C++編輯字符串

fstream Inoutput_file; 
    void BackPatch(int GotoLineNo, string LineNo) 
    { 

    for (int i = 1; i <= GotoLineNo; i++) 
    { 
     char* str = new char[20]; 
     Inoutput_file.getline(str, 20, '\n'); 
     if (i == LineNo-1) 
     { 
      Inoutput_file.seekp(Inoutput_file.tellg()); 
      Inoutput_file.getline(str, 20, '\n'); 
      cout << str << endl;    //prints the correct line 
      Inoutput_file << "Goto " + str <<endl; //donot work 
      cout << "Goto " + str<<endl;  // Prints correct line 
     } 

    } 
    Inoutput_file.seekp(0); 
    Inoutput_file.seekg(0); 
} 

在主:

Inoutput_file.open("example.txt"); 
    BackPatch(3,"Print this to Line 3 instead"); 
    Inoutput_file.close(); 

我也想在這裏指出,我已經打開了「ifstream的」的不同實例相同的文件爲我的計劃的其餘部分工作。

+0

你可能會比 「它不工作」 更具體? – molbdnilo

+0

那就是我想知道的行 Inoutput_file <<「Goto」+ str << endl; 不工作.. – user3765023

+0

我想在這裏提到,我已打開同一個文件與「ifstream」的不同實例用於其餘的程序。 – user3765023

回答

0

fstream Inoutput_file; 無效BackPatch(INT GotoLineNo,串LINENO) {

for (int i = 1; i <= GotoLineNo; i++) 
{ 
    char* str = new char[20]; 
    Inoutput_file.getline(str, 20, '\n'); 
    if (i == LineNo-1) 
    { 
     Inoutput_file.seekp(Inoutput_file.tellg()); 
     Inoutput_file.getline(str, 20, '\n'); 
     cout << str << endl;    //prints the correct line 
     Inoutput_file << "Goto " + str <<endl; //Now it will work fine 
     cout << "Goto " + str<<endl;  // Prints correct line 
    } 

}

相關問題