c - 如何在c中显示printf语句的行号?

标签 c printf scanf

int main() {
int i, repeatName; // ints
char firstName[50]; // array to store users name

// get first name from user
printf("Please enter your first name: ");
scanf("%s", firstName);

// get amount of times user would like to repeat name
printf("How many times would you like to repeat your name?: ");
scanf("%i", &repeatName);

// tell user name has to be repeated at last one
if (repeatName < 1) {
    printf("The name has to be repeated at least one (1) time. Try again: ");
    scanf("%i", &repeatName);
}

// for loop to repeat name 'x' number of times
for (i = 0; i < repeatName; i++) {
    printf("%s \n", firstName);
}
}

例如:如果用户想要显示自己的名字 3 次,则会显示:

Your name 

Your name

Your name 

我怎样才能让它说:

Line 1 Your name

Line 2 Your name

Line 3 Your name 

最佳答案

在循环中使用i变量作为行号

for (i = 0; i < repeatName; ++i)
    printf("Line %d %s\n", i + 1, firstName);

请务必添加 1,因为循环索引从 0 开始。您希望第一行显示“Line 1”,而不是“Line 0”,依此类推。

编辑:当行号超过一位数字时,输出不太漂亮。为了解决这个问题,你可以这样写

for (i = 0; i < repeatName; ++i)
    printf("Line %-6d%s\n", i + 1, firstName);

这使得行号至少占用 6 个字符,并且使行号左对齐:

Line 1     this is my string
Line 2     this is my string
Line 3     this is my string
Line 4     this is my string
Line 5     this is my string
Line 6     this is my string
Line 7     this is my string
Line 8     this is my string
Line 9     this is my string
Line 10    this is my string

关于c - 如何在c中显示printf语句的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38013976/

相关文章:

bash - ANSI 转义在 `printf` 中不起作用

c - 对 txt 文件使用 fscanf 并忽略除字母以外的所有内容

c++ - git pull 显示 .cproject 文件中的 merge 冲突

C结构内存分配

c++ - 链接 C++ 文件

c - 无效的转换标识符 '.'

c - 循环中 printf 的 Getline 行为

scanf - 从 Ada 调用 scanf

c++ - 循环错误试图验证有效输入以在 C++ 中加倍

c - 更新了 Leetcode 上的合并间隔问题 #56(特别是 C 语言)