argc是外部命令參數的個數,argv[]存放各參數的內容。argc >= 1,argv[0]存放程序文件本身。
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int nShowCmd)
szCmdLine = "123.txt 65";
char szCommandLine[100];
char szFirstParam[20];
int nSecondParam;
char *pToken;
strcpy(szCommandLine, szCmdLine); // strtok函數會破壞被分解字符串的完整性。
pToken = strtok(szCommandLine, " ");
if(pToken)
strcpy(szFirstParam, pToken);
pToken = strtok(NULL, " ");
if(pToken)
nSecondParam = atoi(pToken);
szCmdLine:指向應用程序命令行的以NULL終止的字符串,不包括執行文件名。獲得整個命令行,參看GetCommandLine。
要在VC++開發環境中向應用程序傳遞參數,可以單擊菜單【Project】→【Settings】,選擇「Debug」選項卡,在「Program arguments」編輯框中輸入想傳遞給應用程序的參數。
#include <string.h>
#include <stdio.h>
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
void main( void )
{
printf( "%s\n\nTokens:\n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
#include "stdafx.h"
#include <STRING.h>
#include <STDIO.H>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
char *pCmdLine = GetCommandLine();
char sep[] = " ";
char *token = NULL;
char argv[10][10] = {0};
int argc = 0;
token = strtok(pCmdLine,sep);
while (token != NULL)
{
strcpy(argv[argc++],token);
OutputDebugString(token);
token = strtok(NULL,sep);
}
return 0;
}