2013-12-09 36 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跳过换行符。