201403-3 命令行选项

思路

字符串处理

实现


#include <iostream>
#include <string>
#include <map>
#include <cstdio>

using namespace std;

typedef pair<string, string> PAIR;

bool no_arg_options[30];
bool with_arg_options[30];

struct opts {
	map<string, string> opts_map;
	
	void insert(string opt, string arg) {
		if (opts_map.find(opt) == opts_map.end()) {
			opts_map.insert(std::pair<string, string>(opt,arg));
		} else {
			opts_map[opt] = arg;
		}
	}
	
	void out() {
		string res;
		for (map<string, string>::iterator ite = opts_map.begin();
			 ite != opts_map.end();
			 ++ite) {
			if(ite->second == "") {
				res = res + "-" + ite->first + " ";
			} else {
				res = res + "-" + ite->first + " " + ite->second + " ";
			}
		}
		cout << res;
	}

};

int main() {
	
	string consensus_ops;
	getline(cin,consensus_ops);
	
	for (int i = 0;consensus_ops[i];++i) {
		char &c = consensus_ops[i];
		if (c==':') {
			with_arg_options[consensus_ops[i-1] - 'a'] = true;
			no_arg_options[consensus_ops[i-1] - 'a'] = false;
		} else if (c>='a' && c<='z'){
			no_arg_options[c - 'a'] = true;
		}
	}

	
	int num;
	scanf("%d\n",&num);
	
	for (int i = 0;i < num;++i) {

		string command;
		getline(cin, command);
		string::iterator cmd_ite = command.begin();
		
		while (cmd_ite!=command.end() && *cmd_ite != ' ') {
			++cmd_ite;
		}
		++cmd_ite;
		
		cout << "Case " << i + 1 << ": ";
		opts opts_temp;
		while (cmd_ite !=command.end() ) {
			if (*cmd_ite++ == '-') {
				if (no_arg_options[*cmd_ite-'a']) {
					if (cmd_ite!=command.end() && *(cmd_ite + 1) != ' ') {
						break;
					}
					string opt(1,*cmd_ite);
					opts_temp.insert(opt,"");
				} else if (with_arg_options[*cmd_ite-'a']) {
					string opt(1,*cmd_ite);
					if (cmd_ite!=command.end() && *(cmd_ite + 1) != ' ') {
						break;
					}
					while (cmd_ite!=command.end() && *++cmd_ite == ' ');
					string arg;
					while (cmd_ite!=command.end() && *cmd_ite != ' ') {
						if ((*cmd_ite>='a'&&*cmd_ite<='z')
							||(*cmd_ite>='0'&&*cmd_ite<='9')
							||(*cmd_ite=='-')) {
							arg = arg + string(1,*cmd_ite);	
						} else {
							goto end; 
						}
						++cmd_ite;
					}
					if (arg.empty()) {
						goto end;
					}
					opts_temp.insert(opt,arg);
				} else {
					break;
				}
			} else {
				break;
			}
			++cmd_ite;
			while (cmd_ite!=command.end() && *cmd_ite == ' ' ) {
				++cmd_ite;
			}
			if (cmd_ite==command.end()) {
				break;
			}
		}
		end:;
		
		opts_temp.out();
		printf("\n"); 	
	}
	
}

上一篇:模板类类型的智能指针转换


下一篇:[APIO2018] New Home 新家 题解