【问题标题】:Running an .exe from CMD and automatically passing arguments to it从 CMD 运行 .exe 并自动将参数传递给它
【发布时间】:2017-08-12 04:33:00
【问题描述】:

我试图创建一个自定义命令,但它没有按预期工作。 我的文件名为 hello.exe,它位于添加到 PATHC:\ 文件夹中。这是代码:

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main(){
    string name;
    getline(cin, name);
    cout << "Hello, " << name << "!\n";
    return EXIT_SUCCESS;
}

我的意图是像这样从 CMD 运行可执行文件:hello Ulisse,它应该输出 Hello, Ulisse!。但是它似乎不起作用,当我运行 exe 时,我得到一个黑色控制台,等待输入我的名字。 那么,有什么方法可以让参数名称直接从 CMD 传递给变量 name,因此不必在第一次运行命令后输入名称?

【问题讨论】:

  • int main(int argc, char* argv[]) { std::cout &lt;&lt; "Hello, " &lt;&lt; argv[1]'; } 。详情请见this

标签: c++ visual-studio visual-c++ cmd


【解决方案1】:

我只见过使用 argc 和 argv 实现的。以下是来自以下站点http://www.cprogramming.com/tutorial/lesson14.html的sn-p

#include <fstream>
#include <iostream>

using namespace std;

int main ( int argc, char *argv[] )
{
  if ( argc != 2 ) // argc should be 2 for correct execution
    // We print argv[0] assuming it is the program name
    cout<<"usage: "<< argv[0] <<" <filename>\n";
  else {
    // We assume argv[1] is a filename to open
    ifstream the_file ( argv[1] );
    // Always check to see if file opening succeeded
    if ( !the_file.is_open() )
      cout<<"Could not open file\n";
    else {
      char x;
      // the_file.get ( x ) returns false if the end of the file
      //  is reached or an error occurs
      while ( the_file.get ( x ) )
        cout<< x;
    }
    // the_file is closed implicitly here
  }
}

【讨论】:

    【解决方案2】:

    你有两个选择。

    Using argc and argv parameters 或者你可以将所有你想要的输入放在一个 .txt 文件和use < command

    我不认为你在寻找第二个选项,所以尝试第一个,据我所知,这是将参数传递给 C++ 程序的唯一方法

    所以你的代码应该看起来像这样。

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(int argc, char **argv){
        string name;
        if(argc == 1){
            cout << "Whoops, you need to put your name" << endl;
            return EXIT_FAILURE;
        }
        name = argv[1]; 
        cout << "Hello, " << name << "!\n";
        return EXIT_SUCCESS;
    }
    

    您传递给主函数的参数数量中的 argc 和 argv 包含参数,总是至少有一个参数,即 .exe 本身的名称,所以如果您传递一个参数,在您的情况下一个名字,argc 是 2,如果你传递 n 个参数,那么 argc 是 n+1。

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-27
        • 2022-01-05
        • 2018-09-29
        • 1970-01-01
        • 1970-01-01
        • 2017-07-06
        • 1970-01-01
        相关资源
        最近更新 更多