【问题标题】:Why the do while loop is not working properly here?为什么 do while 循环在这里不能正常工作?
【发布时间】:2021-05-29 03:45:20
【问题描述】:
#include<stdio.h>
#include<string.h>

int main()
{
        char letter;
        char answer[10];
        char affirmation[10] = "yes";

        do
        {
                printf("Enter a character: \n");
                scanf("%c",&letter);

                if(letter>=65 && letter<=90)
                {
                        printf("UPPERCASE! \n");
                }
                else if(letter>=97 && letter<=122)
                {
                        printf("LOWERCASE \n");
                }
                else
                {
                        printf("Not an Alphabet \n");
                }

                printf("Wanna try for another Character ? [yes/no] \n");
                scanf("%s",&answer);

        }
        while(strcmp(affirmation,answer) == 0);

        return 0;
}

我正在尝试制作一个程序来判断输入的字符是大写还是小写,然后询问用户是否想再试一次。但它并没有以期望的方式重复。有时它说“以信号 11 终止”。 Here it is.有时它的行为完全不同。 See here.应该怎么做才能得到想要的结果?

【问题讨论】:

标签: c


【解决方案1】:

您应该在 scanf(" %c",&amp;letter); 中的 %c 之前添加一个空格。需要 %c 之前的空间来跳过缓冲存储器中的空白。看看这篇文章了解更多信息。 https://www.codesdope.com/discussion/why-are-you-using-a-space-before-c-in-scanf-c-ch/。 然后您还应该将scanf("%s",&amp;answer); 更改为scanf("%s",answer);,因为数组已经是指向其第一个元素的指针。看看Reading a string with scanf

#include<stdio.h>
#include<string.h>

int main()
{
        char letter;
        char answer[10];
        char affirmation[10] = "yes";

        do
        {
                printf("Enter a character: \n");
                scanf(" %c",&letter);

                if(letter>=65 && letter<=90)
                {
                        printf("UPPERCASE! \n");
                }
                else if(letter>=97 && letter<=122)
                {
                        printf("LOWERCASE \n");
                }
                else
                {
                        printf("Not an Alphabet \n");
                }

                printf("Wanna try for another Character ? [yes/no] \n");
                scanf("%s",answer);

        }
        while(strcmp(affirmation,answer) == 0);

        return 0;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2022-12-12
  • 2016-05-26
  • 1970-01-01
相关资源
最近更新 更多