2017-08-17 139 views
-2

當我寫入文件時是否有任何問題?它只在文件中打印1件東西,但它可以在屏幕上完美打印。我不知道。任何人都可以幫助解決呢?此代碼將打印項目的清單,我從文件中插入可以在屏幕上打印,但只能打印文件中的一件東西

template <class T> 
bool BST<T>::display2(BTNode<T> *cur,int order,int source) 
{ 
ofstream out; 
//if (!out)return false; 
//if (cur == NULL) return false; 
    if (order == 1 && source == 1){//display in ascending order and print to screen 
     if (cur == NULL) return false ; 
     display2(cur->left,order,source); 
     cout << cur->item << ' '; 
     display2(cur->right,order,source); 
     return true; 
    } 
    if (order == 1 && source == 2){//display in ascending order and write to file 
     out.open("student-info.txt"); 
     if(!out){ 
      system("CLS"); 
      cout << "Display Failed!!!\n"; 
      return false; 
     } 
     if (cur == NULL) return false; 
     display2(cur->left, order, source); 
     out << cur->item << ' '; 
     display2(cur->right, order, source); 
     return true; 
    } 
    if (order == 2 && source == 1){//display in descending order and print to screen 
     if (cur == NULL) return false; 
     display2(cur->right, order, source); 
     cout << cur->item << ' '; 
     display2(cur->left, order, source); 
     return true; 
    } 
    if (order == 2 && source == 2){//display in descending order and print to file 
     out.open("student-info.txt"); 
     if (!out){ 
      system("CLS"); 
      cout << "Display Failed!!!\n"; 
      return false; 
     } 
     if (cur == NULL) return false; 
     display2(cur->right, order, source); 
     out << cur->item << ' '; 
     display2(cur->left, order, source); 
     return true; 
    } 
    return true; 

} 
+2

混亂的代碼,很難理解。也許你會覆蓋舊文件,並且必須「追加」模式? BTW系統(「CLS」)用於反模式 –

+0

您可能會考慮將「流出」;「到外層作用域,以便文件在每次函數返回時都不關閉(注意cout不關閉)。這要求您計劃何時關閉文件。 –

+0

你可能會考慮在某些外層作用域使用「std :: stringstream out」。然後計劃在哪裏關閉並輸出內容到ostream中......也許程序結束時(注意cout在程序結束時關閉)。 –

回答

2

你重寫每行文件的內容。 您需要打開追加文件。改線

out.open("student-info.txt"); 

out.open("student-info.txt", std::fstream::app); 

std::fstream::open