【问题标题】:C uninitialized local variable errorC未初始化的局部变量错误
【发布时间】:2014-02-28 22:50:13
【问题描述】:

C 新手仍在学习。 该程序应该在不需要被要求做任何事情的情况下第一次启动。然后它提示用户继续“Y/N”。我一直有错误谁能告诉我为什么它不起作用我不知道如何处理我从中得到的错误。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h> 

void theQnA(char charIn);


int main(void)
{
    int answerint = 0;
    char charIn;
    char anwser;


    printf("Enter a character to be examined: ");
    scanf("%c", &charIn);
    theQnA(charIn);
    while (answerint == 0)
    {
        printf("Would you like to run it again? Y/N\n");
        scanf("%c", &anwser);

        if (anwser == 'y')
        {
            printf("Enter in another character buddy\n");
            scanf("%c", &charIn);
            theQnA(charIn);
        }
        else (anwser != 'y')
        {
            answerint = (answerint--);
        }
    }
    printf("Goodbye\n");

    return 0;
}


void theQnA(char charIn)
{
    if (islower(charIn))
        printf("You have entered in a lower case letter dude\n");
    else if (isdigit(charIn))
        printf("You enterd in a num man\n");
    else if (isupper(charIn))
        printf("Its upper case man\n");
    else if (ispunct(charIn))
        printf("You entered in a punctuation!\n");
    else if (isspace(charIn))
        printf("You enterd in a whitespace dude\n");
    else
        printf("control char/n");
    return;
}

【问题讨论】:

  • 你得到什么错误?
  • 与错误无关的错字:printf("control char/n"); 应该是printf("control char\n");
  • anwser 或 answer...?该代码有更多问题...
  • answerint = (answerint--);:您不应该分配给在同一语句中递减的变量。如果你只想减少answerint,那么answerint--; 会做你想做的事。

标签: c variables loops initialization local


【解决方案1】:

你有else (anwser != 'y')。应该是else if (anwser != 'y'),或者更好的是else。由于循环的结构,提示 Would you like to run it again? Y/N 也将被打印两次。你有很多错误,但这里有一些关于你的循环的建议。

您可以在 while 条件中使用您的 anwser 变量。 answerint 是不必要的。此外,当您键入一个字符并按 Enter 键时,scanf(带有%c)将提取该字符,但将换行符留在缓冲区中。这意味着对scanf 的下一次调用将返回一个换行符,这将使它看起来好像您的程序正在跳过您的输入语句。要解决此问题,请在通话中的 %c 之前添加一个空格:

scanf(" %c", &charIn);

你的逻辑也有点不合时宜。看看这个例子的结构。

printf("Enter a character to be examined: ");
scanf(" %c", &charIn);
theQnA(charIn);

printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
while (anwser == 'y')
{
    printf("Enter in another character buddy: ");
    scanf(" %c", &charIn);
    theQnA(charIn);

    printf("Would you like to run it again? y/n\n");
    scanf(" %c", &anwser);
}

【讨论】:

  • 哦,我现在明白了!为什么里面有空格(“c%”)?
  • 我在回答中解释了。尝试在没有空间的情况下运行您的程序。当您键入一个字符并按 Enter 键时,您正在键入两个字符(字符本身和换行符)。 scanf 通常会忽略空格,但在使用%c 时不会,这就是为什么%c 不能单独使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-03
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多