C: 尝试将 fprintf() 格式字符串拆分为多行并使用 \ 在行首添加制表符来继续行

C: trying to split fprintf() format string into multiple lines with line-continuation using \ adds tabs at the beginning of lines that follow

我正在尝试使用 \ 字符将长 format stringfprintf() 分成多行,如下所示:

fprintf(stdout, "This program take a date supplied by the user in dd/mm/yyyy format...\n\
                        And returns the day of the week for that date using Zeller's rule.\n\n\
                        Enter date in (dd/mm/yyyy) format: ");

这导致 whitespaces 被添加到输出中,如下所示:

This program take a date supplied by the user in dd/mm/yyyy format...
                        And returns the day of the week for that date using Zeller's rule.

                        Enter date in (dd/mm/yyyy) format:

this answer suggests this should work. I also checked this 发帖前先回答。对此的评论提到这种方法...

...suffers from the fact that it breaks if there is any whitespace after the '\'; a bug that can be baffling when it occurs.

cat -A在程序文件上的输出...

^Ifprintf(stdout, "This program take a date supplied by the user in dd/mm/yyyy format...\n$
^I^I^IAnd returns the day of the week for that date using Zeller's rule.\n\n$
^I^I^IEnter date in (dd/mm/yyyy) format: ");$

...\ 后没有空格;尽管它确实在后面的行中引入了 <TAB>s。我正在使用 vim 来编辑我的源文件。

我一直在 Bash 中使用 \ 的续行,并且给人的印象是它与 C 中的 fprintf() 格式字符串的工作方式类似。

我想保持代码的可读性和合理的线宽。除了将长字符串拆分为多个 fprintf().

  1. 这是 printf()/fprintf()
  2. 的标准行为吗
  3. 当我使用 \ 进行续行时,我的代码 vim 是否正常?
  4. 我该如何解决这个问题?

实际可移植性的限制相当低,但实际上您几乎可以肯定地做到:

fprintf(stdout, "This program take a date supplied by the user in dd/mm/yyyy format...\n"
        "And returns the day of the week for that date using Zeller's rule.\n\n"
        "Enter date in (dd/mm/yyyy) format: "
);

如果您确实开始达到这样的连接字符串限制,您还可以这样做:

fprintf(stdout, "%s\n%s\n\n%s",
        "This program take a date supplied by the user in dd/mm/yyyy format...",
        "And returns the day of the week for that date using Zeller's rule.",
        "Enter date in (dd/mm/yyyy) format: "
);

您不需要\,因为它不是宏定义。

只要有任意多的字符串文字,用任意多的空格分隔(新行也是一个空格)。 C 编译器忽略空格。

int main(void)
{
    fprintf(stdout, "This program take a date supplied by the user in dd/mm/yyyy format...\n"
                    "And returns the day of the week for that date using Zeller's rule.\n\n"
                    "Enter date in (dd/mm/yyyy) format: ");
}
int main(void)
{
    fprintf(stdout, "This program take a date"
                    " supplied by the user in dd/"
                    "mm/yyyy format...\n"
                    "And returns "
                    "the "
                    "day of "
                    "the "
                    
                    
                    
                    
                    "week for that "
                    "date using Zeller's rule.\n\n"
                    "Enter date in (dd/mm/yyyy) format: ");
}

https://godbolt.org/z/6ovj3G