C++ 编程接收命令行参数
C++语言接收命令行参数,main() 方法有一种固定的格式,用于接收命令行参数至程序本身:int main(int argc, char* argv[]) {
}
argc [argument count] 是int 类型的变量,即命令行参数的数量计数,比如程序后面输入了3个参数,那么argc = 3.
argv [argument value] 是字符串数组,后面可以跟很多个参数。数组的类型是char*, 每个参数之间用空格分隔开。下面的样例程序,可以输出命令行参数#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "argc = " << argc << endl;
for(int i = 0; i < argc; i++)
cout << "argv[" << i << "] = " << argv[i] << endl;
return 0;
}
你会注意到 argv[0] 显示的是 路径和程序自身,这样程序可以读取argv[0]来获取相关信息了。
虽然我们从命令行获取参数的类型是char*,但是我们有办法转换成其他类型。
我们可以通过atoi(), atol(), atof()来把char*转换成int, long, double类型。#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
for(int i = 1; i < argc; i++)
cout << atoi(argv[i]) << endl;
return 0;
}
在这个例子里面,我们可以发现for是从1开始的,这样我们就可以避开argv[0]了,atoi可以把其它任何类型转换成int,比如输入的是float类型的数字,atoi会转换成int。
如果输入的不是数字,atoi会转换成0.
下面是一个简单的猜数字游戏:#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sstream>
using namespace std;
int main (int argc, char* argv[]) {
string mstr;
srand ( unsigned ( time (NULL) ) );
cout << "Guess a number: " << atoi(argv[1]) << endl;
int n = rand()%100;
if (atoi(argv[1]) == n) {
cout << "Yeah, you win, the number is " << n << endl;
} else {
cout << "Sorry, you lose, the number is " << n << endl;
}
return 0;
}