2016-09-30 49 views
0

我使用Visual Studios在C++中進行編碼,我的代碼只接受名爲「perm15K.txt」的文件。如果我嘗試輸入「perm30K.txt」或「sorted15K.txt」,我的代碼將無法從中讀取。它不會輸出文件錯誤,但它不會讓我輸入要執行的搜索。代碼將只接受一個用戶輸入文件而不是其他代碼

#include "stdafx.h" 
#include "binarysearchtree.h" 
#include "redblacktree.h" 
#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <ctime> 
#include <chrono> 

using namespace std; 

int main() 
{ 
struct bstnodes *root = NULL; 

std::ifstream in; 
std::ofstream out; 

std::stringstream buffer; 
buffer << in.rdbuf(); 
std::string test = buffer.str(); 
std::cout << test << std::endl << std::endl; 

ifstream myFile; 
string input; 
string output; 

cout << "Name of the input file? (ie. perm15K.txt)"; 
getline(cin, input); 
myFile.open(input.c_str()); 

if (myFile.fail()) 
{ 
    cout << "Error with file\n"; 
} 

    for (int j = 0; j < 10; j++) 
    { 

     cout << "Which search? Pleast enter bst or redblack\n"; 

     binarysearchtree temp; 
     redblacktree temp1; 

     while (!myFile.eof()) 
     { 
      while (getline(myFile, input)) { 
       myFile >> input; 
       string words = input; 

       temp.insert(words); 
       temp1.rbinsert(words); 
      }  
     } 
     getline(cin, input); 
      if (input == "bst") 
      { 
       cout << "\nSearch for what word in the tree\n"; 
       getline(cin, input); 
       temp.insert(input); 

       clock_t start_s = clock(); 
       std::cout << "Match Found: " << temp.search(input) <<  std::endl; 
       clock_t stop_s = clock(); 
       double sum = ((double)(stop_s - start_s)); 
       cout << endl << "Time: " << sum << " seconds" << endl; 

       cout << "\nSearch for what word in the tree\n"; 
       getline(cin, input); 
      } 

      if (input == "redblack") 
      { 
       cout << "\nSearch for what word in the tree\n"; 
       getline(cin, input); 
       temp1.rbinsert(input); 
       clock_t start_s = clock(); 
       temp1.rbsearch(input); 
       std::cout << "Match Found: ";      
       clock_t stop_s = clock(); 
       double sum = ((double)(stop_s - start_s)); 
       cout << endl << "Time: " << sum << " seconds" << endl; 
       cout << "\nSearch for what word in the tree\n"; 
       getline(cin, input); 
      } 

     myFile.close(); 
    return 0; 
} 
} 

任何幫助找出我的問題,非常感謝。這就像我被困在無盡的循環中。我一直在試圖找到問題幾個小時,現在找不到解決方案。

回答

0

嘗試查找Visual Studio放置您的可執行文件的位置,並查看其他文本文件是否存在。

另外你的打印語句應該是cout < <「text」< < endl; 如果用「\ n」結束它們,您可能實際上並未刷新可能導致錯誤輸出失敗的打印緩衝區。

+0

我改變了\ n在最後,它沒有什麼區別。文本文件位於可執行文件和解決方案和類文件夾中。 –

+0

當你真的關心獲取調試信息時,使用'cerr',而不是'cout'。 – user4581301

1

也許,如果文件打開失敗,!myFile.eof()永遠不會爲假,因爲myFile.getline()的行爲不如預期的(無限循環)。

如果打開失敗,您應該在錯誤消息之後返回。

此外,你應該只做while(myFile.getline()),而不是檢查eof。

+0

你能在代碼中告訴我你的意思嗎? –

+2

只需刪除'while(!myFile.eof())'行。 –

+0

我這樣做,它並沒有解決任何問題。 –

相關問題