你做任何事情都錯在這裏:
#include <iostream>
using namespace std;
int check_q(char* argv[])
{
float q, qa; // you never assign `q` a value, so the following comparisons make no sense
if(atoi(argv[1]) == q) // you never check argc in main to determine if argv[whatever] is valid. if the array isn't long enough, this will invoke undefined behavior.
{
qa = atof(argv[2]); // you're assigning a value to `qa` declared in this function, leaving the one declared in main unchanged. probably not what you intended
}
// and so on
return qa;
}
int main(int argc, char *argv[])
{
float qa = 0;
check_q(argv); // this function never changes the value of `qa` that's declared in main...
cout << qa << endl; // ... so this will always print 0
return 0;
}
你可能想要做更多的事情:
#include <iostream>
#include <string>
#include <vector>
float check_q(const std::vector<std::string>& args)
{
if(args[1] == "-q")
{
return ::atof(args[2].c_str());
}
else
{
return 0.0f; // or some other default
}
}
int main(int argc, char *argv[])
{
const std::vector<std::string> args(argv, argv+argc);
if(args.size() >= 3) // argv[0] is usually the name of the executable
{
std::cout << check_q(argv) << std::endl;
}
else
{
std::cout << "not enough args" << std::endl;
}
}
一旦你有點更有經驗,你會想要使用庫如GNU getopt或boost::program_options。
在有你的期望沒有得到滿足什麼樣的方式? – 2013-03-04 01:47:08
我認爲你對字符和整數有一些基本的誤解。 「-q」是一個字符串,你應該與strcmp或者它的一個親屬進行比較。 – 2013-03-04 01:48:00
而且你不應該使用==比較int來永遠浮動。 (特別是當其中一個比較項目未初始化時。) – 2013-03-04 01:49:02