gpt4 book ai didi

c - 如何打印行号?

转载 作者:行者123 更新时间:2023-11-30 15:21:38 24 4
gpt4 key购买 nike

我是编程新手,我有一个可以运行的程序,但我需要显示它的行号。我可以使用 C 宏 __LINE__ ?如果是这样,我可以在代码中的哪里插入它,如果不是,我该怎么做才能让程序随代码一起打印出行号?提前致谢。

最佳答案

__LINE__ 宏扩展为整数行号(源文件中的假定行号),因此您可以在任何可用整数的地方很好地使用它:

printf ("This line is %d.\n", __LINE__);

来自 C11 6.10.8.1 强制宏:

__LINE__ The presumed line number (within the current source file) of the current source line (an integer constant).

<小时/>

如果(根据您的评论可能是这种情况),您只需要一个可以输出行号的程序,我建议不要使用__LINE__那个。

相反,最好让程序记录它所在的行,并在该行本身之前输出它。例如,参见:

#include <stdio.h>

int main (void) {
static char buff[100000];
int lineNum = 0;
FILE *fp = fopen (__FILE__, "r");
if (fp != NULL) {
while (fgets (buff, sizeof (buff), fp) != NULL) {
printf ("%7d: %s", ++lineNum, buff);
}
fclose (fp);
}
return 0;
}

关于c - 如何打印行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29529786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com