0

我正在尝试使用如下所示的字符将 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. 我该如何解决这个问题?
4

2 回答 2

2

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

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

于 2020-10-02T19:10:18.157 回答
2

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

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: "
);
于 2020-10-02T18:59:03.630 回答