简体   繁体   中英

How can i combine the effects of options passed in the command line on strings?

I have a function that receives some flags and based on these flags it formats the line to be printed as output. The problem is, these flags are independent of each other. In other words, the output can be formatted as many ways as there are combinations of these flags.

There 3 flags: bflag, nflag and sflag. If bflag is 1, nflag is overidden. But we can have b and s at the same time (or n and s), and both manipulate the output line in its own way. How can i handle this without nesting all the possibilites in if statements ( the only way i can think of) ?

Here's the function that receives the non-formatted string and the flags:

void outputLine(int *index, char buffer[], int bflag, int nflag){ //processes the options passed in the command line to create the output
  if (nflag){
    indexedLineout(index, buffer);
  }
  else if (bflag){
    bprint(index, buffer);
  }
  else{//no options
    printf("%s", buffer);
  }
}

And here's indexedLineout():

void indexedLineout(int *index, char buffer[]){//adds an index to the beginning of the line
  printf ("%*d\t%s", 6, *index, buffer);
  (*index)++;//increment the index
}

I dont think it is relevant to show bprint() as it has a very sinmilar behaviour to indexedLineOut().

If i want to add the s flag i mentioned above, that basically does not print anything if the previous output was an empty line, and make sure that it also works in conjunction with the other flags, in other words, make sure it can print numbered lines but not adjacent empty ones, how can i achieve that?

There 3 flags: bflag, nflag and sflag. If bflag is 1, nflag is overidden. But we can have b and s at the same time (or n and s), and both manipulate the output line in its own way. How can i handle this without nesting all the possibilites in if statements ( the only way i can think of) ?

You have two separate formatting functionalities controlled by three options, in a particular way that should be relatively clean to handle. You should be able to simply iterate over the lines, and for each one:

  1. Compress blank lines if appropriate (flag s) . If the line is blank, the previous was also blank, and the s flag is in effect, then skip this line. Otherwise,
  2. Print the line number if appropriate (flags n,b) .
    • if the n flag is in effect and b is not, then print the line number, else
    • if the b flag is in effect and the line is not blank then print the line number.
  3. Print the line itself .

I don't think I'd even split that up into separate functions, but if you do then I'd recommend choosing functions that fit cleanly into that scheme.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM