【问题标题】:How do I create multiple columns in C for my code如何在 C 中为我的代码创建多个列
【发布时间】:2021-01-25 19:42:09
【问题描述】:

我目前正在尝试用 C 语言创建一个程序:

首先,让您的过滤器在单列中打印所有输入数字,并且小数点对齐(以及所有 13 位精度)。

其次,创建三列输出(小数点对齐)。请务必考虑到最后一行不需要包含三列。

第三,有一个命令行参数确定列数。

第四,有一个环境变量决定列数。

第五,让命令行参数或环境变量确定输出数字的精度。

最后,检查配置文件(在检查环境变量和命令行参数之前),如果它退出,让它的值覆盖默认值。

到目前为止,我正在尝试执行第 2 到第 4 步,但无法创建多个列。然后我必须制作列变量的#,以便它们可以通过命令行或环境变量进行更改。列的默认值需要为 3。

我的代码:

#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\n",  (x + incBy));
    }
    return 0;
}

【问题讨论】:

  • ????????请在此处以纯文本形式发布代码、错误、示例数据或文本输出,而不是难以阅读的图像,不能复制粘贴以帮助测试代码或在答案中使用,并且是那些依赖的人的障碍在屏幕阅读器或翻译工具上。您可以编辑问题以在问题正文中添加代码。为了便于格式化,请使用{} 按钮标记代码块,或者使用四个空格缩进以获得相同的效果。 屏幕截图的内容无法搜索、作为代码运行或复制和编辑以创建解决方案。
  • 已修复,抱歉
  • 在if ((fp=.... 行之后有一个( 而不是{。
  • 假设没有语法错误...您可以通过在 while 循环中的每 3 次迭代中仅打印 '\n' 字符来制作 3 列。在你开始工作后用你的列 var 替换 3 应该没问题。

标签: c formatting


【解决方案1】:
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) ? '\t' : '\n', !fo ? stdout : fo);
    }
}

https://godbolt.org/z/czc17q

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-29
    • 2019-02-20
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多