通常情況下,我們定義的main函數都只有空形參列表:
int main(){...}
然而,有時我們確實需要給mian傳遞實參,一種常見的情況是用戶設置一組選項來確定函數所要執行的操作。例如,假定main函數位於可執行文件prog內,我們可以向程序傳遞下面的選項:
prog -d -o ofile data
這些命令行選項(即在cmd中輸入的)通過兩個(也可以是其他任意個)形參傳遞給main函數:
int main(int argc,char *argv[]){...}
第二個形參argv是一個數組,它的元素是指向C風格字符串的指針;第一個形參argc表示數組中字符串的數量。因為第二個形參是數組,所以main函數也可以定義成:
int main(int argc,char **argv){...}
其中argv指向char*。
當實參傳給main函數之后,argv的第一個元素指向程序的名字或者一個空字符串,接下來的元素依次傳遞給命令行提供的實參,最后一個指針之后的元素保證為0。
以上面提供的命令行為例,argc應該等於5,argv應該包含如下的C風格字符串:
argv[0] = "prog";
argv[1] = "-d";
argv[2] = "-o";
argv[3] = "ofile";
argv[4] = "data";
argv[5] = 0; //這個參數和我們沒什么關系,只是為了保證最后一個指針之后的元素為0而已。不用管。
需要傳遞參數的main函數的程序代碼片段如下:
int main(int argc, char **argv)
{
//open and check both files
if (argc != 3) //pass three arguments to main,if not, print an error message
throw runtime_error("wrong number of arguments");
ifstream map_file(argv[1]); //open transformation file
//Note:argv[0] stores C-style characters which is the name of the program that contains main() function,so the fisrt file is stored in argv[1]
if (!map_file) //check that open succeeded
throw runtime_error("no transfrom file");//you don't need to care about it now
ifstream input(argv[2]); //open file of text to transform,the second file,also the third parameters in argv
if (!input) //check that open succeeded
throw runtime_error("no input file");
word_transform(map_file, input);
getchar();
//return 1; //exiting main will automatically close the files
}
//wu xing zhuang bi, zui wei zhi ming: )
為了運行此程序,我們必須輸入main所需的參數,否則會拋出runtime_error異常,甚至出現意想不到的錯誤。
步驟如下:
- 打開cmd,用cd命令將當前路徑調至帶有要編譯的cpp文件的目錄下。如,假設我要編譯的文件為word_transform.cpp,,該文件在G:\C++projects\Githubpath\learnCPP\code\L11 Associative Container\word_transform\word_transform目錄下,則輸入的命令為
cd G:\C++projects\Githubpath\learnCPP\code\L11 Associative Container\word_transform\word_transform
- 編譯此文件。我使用的編譯器版本為gcc 4.9.2,輸入的命令為
g++ word_transform.cpp
如果要支持c++ 11,部分編譯器需要在后面加上-std=c++0x,如:
g++ word_transform.cpp -std=c++0x
- 向main函數傳遞參數。假設包含main函數的文件為word_transform.cpp,要傳遞的參數為rules和text,那么傳遞參數的命令為:
word_transform rules text
此處argv[0] = "word_transform",argv[1] = "rules",argv[2] = "text"。
注1:如果要編譯多個文件,應將所有文件都編譯。例如,假設要編譯的文件有test.h,test1.cpp,test2.cpp,textMain.cpp,要傳遞的參數為hello.txt,則編譯的命令為:
g++ test.h test1.cpp,test2.cpp,testMain.cpp -std=c++0x
注2:在包含多個文件的情況下,盡管main函數在testMain.cpp中,調用"testMain hello.txt"也無法成功傳入參數。解決辦法如下:
由於在Windows系統下將所有文件編譯后會生成一個a.exe文件,因此,我們可以向該文件傳遞參數,命令如下:
a hello.txt
以上就是c++向main函數傳遞參數的方法了,在UNIX系統中與此有所不同,等以后遇到再說吧。
這篇博文的實例我已上傳至github,這是一個文本轉換的程序,地址為https://github.com/Larry955/learnCPP/tree/master/code/L11%20Associative%20Container/word_transform
歡迎感興趣的讀者下載。