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;
}