Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

formatting - How do I create multiple columns in C for my code

I am currently trying to create a program in C:

First, get your filter to print all of the input numbers in a single column with their decimal points lined up (and all 13 digits of precision).

Second, create three columns of output (with the decimal points lined up). Be sure to take into consideration that the last row does not need to have three columns.

Third, have a command line argument determine the number of columns.

Fourth, have an environment variable determine the number of columns.

Fifth, let a command line argument or an environment variable determine the precision of the output numbers.

Last, check for the configuration file (before checking for the environment variables and the command-line arguments) and, if it exits, have its values override the default values.

So far I have this, I'm trying to do steps 2 - 4, but I have trouble creating multiple columns. I then would have to make the # of column variables so that they can be changed by a command line or environment variable. The default of columns needs to be 3.

My code:

#include <stdlib.h>
#include <stdio.h>


int main(int argc, char *argv[]) {
    // Set the default value.
    int incBy = 0; here 
    // Override the default value with a value from the configuration file.
    FILE *fp;
    if ((fp = fopen("incrementor.cfg", "r")) != NULL) 
{

        fscanf(fp, "%d", &incBy);
    }
    // Override the default value with an environment variable value.
    char * op;
    if ((op = getenv("GET_COLUMNS")) != NULL) 
{
        //get an operand from the environment
        incBy = atoi(op);
    }
    //Get a command line argument (if it exists)
    if (argc > 1) {
        //get an operand from the command line 
        incBy = atoi(argv[1]);
    }
    //Process the stream of input numbers.
    double x;
    while (scanf("%lf", &x) != EOF) {
        printf("%18.13f
",  (x + incBy));
    }
    return 0;
}
question from:https://stackoverflow.com/questions/65891371/how-do-i-create-multiple-columns-in-c-for-my-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
void printdoubles(FILE *fo, const char *fmt, const double *arr, size_t size, size_t ncolumns)
{
    for(size_t index = 0; index < size; index++)
    {
        fprintf(!fo ? stdout : fo, fmt, arr[index]);
        fputc(((index + 1) % ncolumns) ? '' : '
', !fo ? stdout : fo);
    }
}

https://godbolt.org/z/czc17q


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...