将 argv 作为存储字符串传递给函数
passing an argv to a function as a stored string
谁能解释一下为什么getMessage() 函数中的cout 没有读出。我的目标是将 argv[i] 作为先前存储的值传递。
到目前为止,这是我的代码。我是命令行参数的新手,任何帮助都会很棒。
#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()
。它应该更像这样:
#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;
}
谁能解释一下为什么getMessage() 函数中的cout 没有读出。我的目标是将 argv[i] 作为先前存储的值传递。
到目前为止,这是我的代码。我是命令行参数的新手,任何帮助都会很棒。
#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()
。它应该更像这样:
#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;
}