Question

I am trying to make a basic file browser in C++, however it does not work very well. I have put an image at the bottom to show what is happening as it is quite hard to explain:

#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

Was it helpful?

Solution

It seems you're making the common mistake of not watching for line endings when reading user input.

If the user puts in 1 what's really in the input buffer is 1\n (they had to push enter, right?) and you call getchar to get the 1 so the buffer now contains \n. Then when you call getline to get the path, it's going to read until the first new line. So it gets an empty string.

After your getchar you should call ignore to skip over the newline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top