main與WinMain命令行參數(shù)提取和strtok的用法
argc是外部命令參數(shù)的個(gè)數(shù),argv[]存放各參數(shù)的內(nèi)容。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函數(shù)會(huì)破壞被分解字符串的完整性。
pToken = strtok(szCommandLine, " ");
if(pToken)
strcpy(szFirstParam, pToken);
pToken = strtok(NULL, " ");
if(pToken)
nSecondParam = atoi(pToken);
szCmdLine:指向應(yīng)用程序命令行的以NULL終止的字符串,不包括執(zhí)行文件名。獲得整個(gè)命令行,參看GetCommandLine。
要在VC++開(kāi)發(fā)環(huán)境中向應(yīng)用程序傳遞參數(shù),可以單擊菜單【Project】→【Settings】,選擇「Debug」選項(xiàng)卡,在「Program arguments」編輯框中輸入想傳遞給應(yīng)用程序的參數(shù)。
#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;
}
posted on 2012-03-29 20:15 tqsheng 閱讀(826) 評(píng)論(3) 編輯 收藏 引用