c++中main()函数返回值只能是int。
参数可以为空,或者void。即:
int main()
int main(void)
也可以带有参数,有两种形式,如下:
int main(int argc, char **argv)
int main(int argc, char *argv[])
int argc, char *argv[] 用于运行时,把命令行参数传入主程序。
argc -- 命令行参数总个数,包括 可执行程序名。
argv[i] -- 第 i 个参数。
argv[0] -- 可执行程序名。
#include <iostream>
#include <fstream>
#include <cstdlib>
int main(int argc, char *argv[])
{
using namespace std;
if(argc == 1)
{
cerr << "Usage: " << argv[0] << " filename[s]\n";
exit(EXIT_FAILURE);
}
ifstream fin;
long count;
long total = 0;
char ch;
for(int file = 1; file < argc; file++)
{
fin.open(argv[file]);
if(!fin.is_open())
{
cerr << "Could not open " << argv[file] << endl;
fin.clear();
continue;
}
count = 0;
while(fin.get(ch))
count++;
cout << count << " chracters in " << argv[file] << endl;
total += count;
fin.clear();
fin.close();
}
cout << total << " characters in all files\n";
return 0;
}
运行情况如下: