tqsheng

go.....
随笔 - 366, 文章 - 18, 评论 - 101, 引用 - 0
数据加载中……

main与WinMain命令行参数提取和strtok的用法

    int main(int argc, char *argv[])

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

posted on 2012-03-29 20:15 tqsheng 阅读(789) 评论(3)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理