【问题标题】:C++ read "enter" in command lineC++ 在命令行中读取 \"enter\"
【发布时间】:2022-11-02 02:14:10
【问题描述】:

我有一个非常简单的问题。

我有一个如下项目:

#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;
}

我的问题是:在命令行中,如果我点击进入在我的键盘上,我不想在file_name 中读取任何内容,然后它会自动加载默认文件。目前的情况是它会等到我输入一些东西。我怎样才能做到这一点?

【问题讨论】:

  • 什么是“默认文件”?
  • cin&gt;&gt; file_name; 您可能希望使用 std::getline() 来允许用户输入带有空格的文件名/路径。

标签: c++ shell command


【解决方案1】:

operator&gt;&gt; 丢弃前导空格,然后读取直到空格。进入生成一个' ' 字符,operator&gt;&gt; 将其视为空格。

对于您想要做的事情,请改用std::getline(),例如:

#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";
    ifstream file(file_name);
    if(file.good()){
        cout << "File can be loaded";
    }
    else{
        cout << "Default file will be loaded";
    }
    return 0;
}

【讨论】:

  • cout &lt;&lt; "Default file will be loaded"; 可能需要更改此消息。
猜你喜欢
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 2019-02-07
  • 2015-12-23
  • 1970-01-01
  • 2016-06-14
  • 2010-12-02
  • 1970-01-01
相关资源
最近更新 更多