您的位置:首页 > 编程语言 > C语言/C++

C++02、带参main函数的使用

2016-06-21 15:46 453 查看
下面是一个简单的示例,示例中会使用到string和list,这两个类的使用会在后面介绍。现在看看就可以。具体示例如下:

#include<windows.h>
#include <iostream>
#include <list>
#include <string.h>
using namespace std;

class Premain
{
public:
Premain(){cout << "please input two pramaters to run the program:" <<endl;}
};

Premain pre; //全局对象,先于main 生成。

int main(int argv ,char** argc)
{
cout << "hello !" << endl;

if(argv > 1)
{ //argv 属于正常计数,有几个参数就是几

if(strcmp(argc[1],"abc")==0) //如果第一个参数正确
{

string words[]={"statly","pumb","buck","multimap","test"};
size_t words_size = sizeof(words)/sizeof(string);
cout <<"total num =" <<words_size << endl;
string insert1("instert!");

list <string> words2 (words ,words+words_size); //copy words to list
list <string>::iterator ii; //迭代器
for(ii=words2.begin();ii!=words2.end();++ii)
cout << *ii <<endl ;
cout << endl;

if(argv > 2)
{
if(strcmp(argc[2],"123321")==0) //且第二个参数正确
{
words2.insert(words2.begin(),insert1); //在迭代器之前插入元素
cout << "after insert1 :" << endl;
for(ii=words2.begin();ii!=words2.end();++ii)
cout << *ii <<endl ;
cout << endl;

words2.insert(words2.end(),5,"+++++"); //在指针之前插入元素 尽量保持const ,否则在vs2010或13中可能编译不过
cout << "after insert2 :" << endl;
for(ii=words2.begin();ii!=words2.end();++ii)
cout << *ii <<endl ;

ShellExecute(NULL,"open","http://blog.csdn.net/thedarkfairytale?viewmode=contents",NULL,NULL,SW_SHOW);//对于http 默认调用浏览器启动
}
}
}
}

cout<< "the command line parameters are: "<<endl;
for(int i=0;i<argv;++i)
{
cout << *argc << endl;
++argc;
}
return 0;
}

输出结果如下:



上面这是个简单的示例,下面是实际应用的一种,尤其在使用命令行的时候,这种用法较多 ,如网络连接:

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

{

const
char* hostname = (argc > 1) ? argv[1] : "127.0.0.1";
const intport = (argc > 2)
? atoi(argv[2]) : 10010;

/*

其他操作

*/

return 0;

}

当然自己写一些小程序的时候会经常用到命令行加参数,当然刚学编程的时候,了解命令行更多的是在linux下,这种方式还是比较常见。

4000

2、关于数的溢出:

比如short 为16位,能表示的最大数字是2^16 -1 = 32767 ,如果超出则会溢出。另外int也是一个需要主要的数据类型,数据量过大时也会经常溢出,出现数值错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: