c - How to send elements of the structure to switch -
currently parsing command line arguments in c program, , learn you, how in best way, below have attached source code, program processes input looking
wae0500 /f1.txt /d; comment1 comment2
the result
- debug:1
- help:0
- file_used:1
- read:0
- write:1
when flags received, work 2 conditions: either write or read, switch between fields of structure, code below wrong know, hope understand goal:
switch(flags){ case(flags.write): // smth break; case(flags.write): // smth break; }
and here complete program
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef enum { false, true } bool; typedef struct { bool debug; bool help; bool file_used; bool read; bool write; }flags; void parse_input(flags *flag, int argc, char *argv[], char *file_name); int main(int argc, char *argv[]) { flags flag = { 0,0,0,0,0 }; flags *flag_ptr = &flag; char file_name[96]; parse_input(&flag, argc, argv, file_name); return 0; } void parse_input(flags *flag, int argc, char *argv[], char *file_name) { int = 1; int j = 0; char cur_ch; while (i != argc) { cur_ch = argv[i][j]; switch (cur_ch) { case 'w': flag->write = true; break; case'r': flag->read = true; break; case '/': j++; cur_ch = argv[i][j]; switch (cur_ch) { case 'd': flag->debug = true; break; case 'f': flag->file_used = true; if (argv[i][j + 1] != ' ') strcpy(file_name, &argv[i][j + 1]); break; case 'h': flag->help = true; break; default: printf("bad argument: %s\n", argv[i]); } break; case ';': // stop while = argc - 1; break; default: printf("bad argument: %s\n", argv[i]); } i++; } }
such option can temporary solution, learn how correctly
char command_type = '\0'; if (flag.write) command_type = 'w'; else if(flag.read) command_type = 'r'; switch (command_type) { case 'w': //do smth break; case 'r': //do smth break; }
upd2:
enum flagtype { read, write, file_used, debug, }; struct s { flagtype type; union { // write in union?; }; };
Comments
Post a Comment