Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ read "enter" in command line

I have a very simple question.

I have a project like below:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    string file_name;
    cin >> file_name;
    ifstream file(file_name);
    if(file.good()){
        cout << "File can be loaded";
    }
    else{
        cout << "Default file will be loaded";
    }
    return 0;
}

In the command line, if I just hit Enter on my keyboard, I want to read nothing in file_name and then it will load a default file automatically. The current situation is it will wait until I type in something.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do this?

>Solution :

operator>> discards leading whitespace first (unless the skipws flag is disabled on the stream), and then reads until whitespace is encountered. Enter generates a '\n' character, which operator>> treated as whitepace.

For what you want to do, use std::getline() instead, eg:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    string file_name;
    getline(cin, file_name);
    if (file_name.empty()) {
        file_name = "default name here";
        cout << "Default file will be loaded" << endl;
    }
    else {
        cout << file_name << " will be loaded" << endl;
    }

    ifstream file(file_name);
    if(file.is_open()){
        cout << "File is opened" << endl;
    }
    else{
        cout << "File is not opened" << endl;
    }

    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading