Home > Blockchain >  C read "enter" in command line
C read "enter" in command line

Time:11-02

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.

How can I do this?

CodePudding user response:

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;
}
  • Related