gpt4 book ai didi

c - 查询用户继续在 C 中打印

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:21 25 4
gpt4 key购买 nike

我正在编写一个从 0 开始打印的程序。
它最多打印 15 个并向用户询问一个y/n 问题。

  • 如果 y 该程序打印下一个 15。
  • 如果n 程序停止。

我写的程序不工作。

帮助解决这个问题。

int main()
{
int i=0,k=1;
char ans;

while(k=1)
{
i++;
printf("\n%d",i);

if(i%15==0)
{
printf("\nDo you want to continue?(y/n): ");
scanf("%c",ans);
ans = toupper(ans);
if(ans=='Y') {
continue;
}
else if(ans=='N') {
k=0;
}
}
}
}

--------------------------------编辑------------ --------------------------将代码更改为@Programmer400。同样是 15-->3。现在我的电脑打印

1
2
3
Do you want to continue?(y/n): y

4
5
6
Do you want to continue?(y/n):
7
8
9
Do you want to continue?(y/n): y

首先它打印到 3 并询问。在 Y 之后,它打印到 6 并询问,然后在没有任何输入的情况下打印到 9 并询问。注意第二个问题中缺少的 y。

最佳答案

我在下面提供了一个可运行的 C 程序,它可以执行您在问题中指定的任务。

我已努力忠实于您在原始代码示例中使用的函数,并且我还注意只添加(而不是删除代码)。

在评论中,我已经解释了我添加的不在您的原始代码示例中的代码行。

#include <stdio.h>

int main(void)
{
int i = 0, k = 1;
char user_input;
char ans;

while(k == 1)
{
i++;
printf("%d\n", i);

if (i % 15 == 0)
{
printf("Do you want to continue? (y/n/Y/N): ");
scanf(" %c",&user_input); // Keep the whitespace in front of the %c format specifier -- it's important!
getchar(); // Consume the newline character left in the buffer by scanf()

// Check if user input is already capitalized
if (user_input >= 65 && user_input <= 90)
// If it is, keep it capitalized
ans = user_input;
else
// If it isn't, capitalize it
ans = toupper(user_input);

if (ans=='Y')
{
// Allow the loop to continue
continue;
}
else if (ans == 'N')
{
// Inform the user that execution is ending
printf("Exiting loop... ending program.\n");
// Consider removing 'k' entirely, just use a 'break' statement
k = 0;
}
else
{
// Inform the user that the input was not recognized (if not y/n/Y/N...)
printf("User input not recognized... please provide input again.\n");
// Decrement 'i' so that the user is forced to provide input again...
i--;
// Allow the loop to continue
continue;
}
}
}
}

有用的注释:

    当您使用字符格式化程序读取用户输入时,
  1. scanf 会在缓冲区中留下一个换行符。即……

    %c, %n, and %[] are the 3 specified expectations that do not consume leading whitespace -- From a comment on this StackOverflow answer.

  2. 请记住,如果您想退出 while 循环,只需插入一个 break 语句即可。这样,您不必更改 k 的值(这是相当模糊的)来结束循环,并且代码更具可读性,因为显式的 break 语句是更难误解。在这个简单的例子中,k 的使用很容易理解(所以暂时不要太担心)。

  3. 如果您打算从用户那里读取字符串输入(即字符数组),那么我建议您使用 fgets() 而不是 scanf( )this StackOverflow answer 中提供了关于 fgets()scanf() 相比优点的讨论。 .此外,重要的是要认识到,即使您可以使用gets() 来执行类似的操作,它也是非常危险的,并且不建议这样做。查看 top two answers to this StackOverflow question 提供的解释.

关于c - 查询用户继续在 C 中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38345044/

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