【问题标题】:passing an argv to a function as a stored string将 argv 作为存储字符串传递给函数
【发布时间】:2017-03-21 12:53:00
【问题描述】:

谁能解释为什么 getMessage() 函数中的 cout 没有读出。我的目标是将 argv[i] 作为先前存储的值传递。

到目前为止,这是我的代码。我是命令行 args 的新手,任何帮助都会很棒。

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

void getMessage(string action);

int main(int argc, char* argv[])
{

    string action = argv[1];    
    cout << action << endl;
}

void getMessage(string action)
{
    cout << "I said " << action << endl;

}

【问题讨论】:

  • 你不要打电话给getMessage
  • 你在运行时是否给它命令行参数?
  • @Galik 这不是重点。

标签: c++ visual-studio command-line command


【解决方案1】:

它确实有效,因为您实际上根本没有调用getMessage()。它应该更像这样:

#include <iostream>
#include <string> 

using namespace std;

void getMessage(const string &action);

int main(int argc, char* argv[])
{
    if (argc > 1)
    {
        string action = argv[1];
        getMessage(action);
    }
    else
        cout << "no action specified" << endl;

    return 0;
}

void getMessage(const string &action)
{
    cout << "I said " << action << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多