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/