首页 > 解决方案 > C:尝试使用 \ 将 fprintf() 格式字符串拆分为多行并在行的开头添加制表符

问题描述

我正在尝试使用如下所示的字符将 long format stringto拆分fprintf()为多行:\

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:

这个答案表明这应该有效。在发布到这里之前,我还检查了这个答案。对它的评论提到这种方法......

...遭受这样一个事实,即如果在“\”之后有任何空格,它就会中断;发生时可能会令人困惑的错误。

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,并认为它与fprintf()C 中的格式字符串类似。

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

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

标签: cgccvimprintfline-continuation

解决方案


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

只需将任意数量的字符串文字用任意数量的空格分隔即可(新行也是空格)。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


推荐阅读