【问题标题】:Take file as an input from the command line c++将文件作为命令行c ++的输入
【发布时间】:2015-03-11 23:43:47
【问题描述】:

目前,我有代码使用 cin 来获取文件名,以便在程序执行时用作输入。我想拥有它,这样当我运行程序时,我可以添加文件重定向和文件名并像这样运行它:./a.out 。如何使用重定向将我的文件输入到我的代码中。

这是我当前如何接受输入的示例:

int main(){
  
    std::string filename;
	std::cin >> filename;
	std::ifstream f(filename.c_str());
  
 }

【问题讨论】:

    标签: c++ file-io stdin


    【解决方案1】:

    这样做

    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main()
    {
        std::string line;
    
        std::cout << "received " << std::endl;
    
        while(std::getline(std::cin, line))
        {
            std::cout << line  << std::endl;
        }
    
        std::cout << "on stdin" << std::endl;
    }
    

    您不需要自己打开文件,因为在命令行上使用&lt; 会在stdin 上将文件内容传递给您。

    此代码有一个缺点,即如果您未在 stdin 上输入任何内容,它会冻结。检测stdin 为空只能以不可移植的方式实现(参见here)。

    最好接受你的文件名作为普通命令行参数并在你的程序中打开它。

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 2010-09-16
      • 2019-03-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 2012-02-18
      • 2014-05-15
      相关资源
      最近更新 更多