2013-12-09 64 views
-1

我想在C++中製作一個基本的文件瀏覽器,但它不能很好地工作。我已經把圖像的底部,顯示正在發生的事情,因爲它是非常難以解釋:C++文件瀏覽器錯誤

#include <iostream> 
#include <sstream> 
#include <fstream> 

#define NULL(str) (str == "") 

using namespace std; 

void read(string *memory); 
void write(string *memory); 

int main(void){ 
    string memory; 
    for(;;){ 
     cout << "Please select your option:" << endl << "1: read a file - this text will be stored in memory until another file is read" << endl << "2: write text to a file - use ~MEM to get memory" << endl; 
     char opt = getchar(); 
     switch(opt){ 
     case '1': 
      read(&memory); 
      break; 
     case '2': 
      write(&memory); 
      break; 
     default: 
      cout << "The option was unrecongized" << endl << endl; 
      break; 
     } 
    } 
    return 0; 
} 

void read(string *memory){ 
    string path; 
    cout << "Please enter the path of the file you would like to read" << endl; 
    getline(cin, path); 
    string str; 
    string input; 
    ifstream file; 
    file.open(path); 
    if(!file.is_open() || !file.good()){ 
     cout << "An error occured while reading the file" << endl << endl; 
    } 
    else{ 
     while(getline(file, str)){ 
      input += str; 
     } 
     file.close(); 
     if(NULL(input)){ 
      cout << "The input from the file is empty" << endl << endl; 
     } 
     else if(input.size() > 1000){ 
      cout << "The file is too large: it is bigger than 1000 characters" << endl << endl; 
     } 
     else{ 
      *memory = input; 
      cout << input << endl << endl; 
     } 
    } 
} 

void write(string *memory){ 
    string path; 
    cout << "Please enter the path of the file you would like to write to" << endl; 
    getline(cin, path); 
    ofstream file; 
    file.open(path); 
    if(!file.is_open() || !file.good()){ 
     cout << "The file could not be written to" << endl << endl; 
    } 
    else{ 
     string input; 
     getline(cin, input); 
     if(input == "~MEM"){ 
      file << *memory; 
     } 
     else{ 
      file << input; 
     } 
     file.close(); 
    } 
} 

My Problem

+0

你至少可以試圖解釋這個問題 –

+1

你爲什麼要傳遞指針?爲什麼不正確地返回對象? –

回答

2

看來你正在閱讀的時候使不看的行結束的常見錯誤用戶輸入。

如果用戶將在1什麼是真正的輸入緩衝區1\n(他們不得不按回車,對吧?),你叫getchar得到1因此緩衝區現在包含\n。然後,當您撥打getline獲取路徑時,它將讀取直到第一個新行。所以它得到一個空字符串。您可以撥打ignore跳過換行符。