Categories: C/C++ | Tags: | Views: 897

题目写得有点拗口, 其实就是读取形如这样的参数行:

./XXX -i input -o output -l label

这种方法可以不论参数选项的顺序(当然,input还是要跟在-i后面),并可以忽略错误的参数选项。

这个是C++的版本,其他语言版本可以依次类推。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
bool parseCommandLine(int argc, char * argv[]) {
    int argct = 1;
    string temp;
    if (argc==1) {   // 没有给出参数的时候给出一些程序的说明
        cout << "n  -- XXX programs --n";               
        cout << "  给出你程序的信息和说明nn";
        cout << "  程序各参数的意义:n"
        cout << "  -i <file>      Input filen";  
        cout << "  -o <file>      Output filen";
        cout << "  -l <label>     Label for this runn"; 
        cout << "n";
        cout << "  程序的用法:n"
        cout << "  ./XXX -i inputn";
        cout << "  ./XXX -i input -o outputn";
        cout << "  ./XXX -i input -o output -l firstn";                       
        cout << "n";
        return false; 
    } else {       // 进行参数选项和参数的读取
        while (argct < argc) {
            temp = argv[argct]; // 存放参数选项(如-i,-o,-l)
            if (temp == "-i") {
        argct++;         //从参数选项指向参数
        ioparm.input = argv[argct]; //将读取的参数存入全局变量中
        // 可以对参数进行检测,如果不符合要求就直接return false.
            } else if (temp == "-o") {
        argct++; 
        ioparm.output = argv[argct];
            } else if (temp == "-l") {
        argct++; 
        ioparm.label = argv[argct];
            } else { 
        cout << " Warning: ignored argument " << argct << " : " << temp << endl;
        // 如果不是给定的参数选项,则忽略这一个参数,如:
        // ./XXX -i input -t a -o output  这里的 -t 和 a将被逐个忽略
        }
            argct++;            //指向下一个参数选项
        }
    }
    //读完了之后可以对必须的参数予以检测, 如:
    //或者在上面读取的时候就可以检测, 如果不符合要求就直接return false
    if (ioparm.input.empty()) {
    cout << " Error: argument "-i" is essential. " << endl;
    return false;
    }
    return true;
}
这篇文章来自 迷途知返(PWWANG.COM), 转载请注明出处。 版权说明

  1. March 5th, 2009 at 11:03
    Reply | Quote | #1

    pwwang也研究C++么?那太好了,以后有问题和你讨论下下哈…

    • March 5th, 2009 at 11:44
      Quote | #2

      谈不上研究,随便玩玩

;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)

你可以使用@somebody:开头, 来邮件通知somebody你回复了他的留言(用户名区分大小写).