Char变量如何在C中起作用

时间:2014-02-09 15:25:05

标签: c

我想要完成的是提示用户他们想要再次运行程序的问题。他们要么输入y,要么输入n。如果是,则重新运行该程序。如果不是,则停止程序。除了这两个之外的任何东西都会提示错误并再次提出问题。我已经习惯了C#,其中字符串并不复杂,但在C中,我认为技术上不是字符串,所以我们必须使用char数组或char指针。我试过这两个,没有一个按我想要的方式工作,但我可能是问题。这就是我所拥有的。

char answer[1] = "a";

while (strcmp(answer, "y") != 0 || strcmp(answer, "n") != 0)
{
    printf ("\n\nWould you like to run the program again? Type y or n. Then, hit Enter.");
    scanf ("%c", answer);

    if (strcmp(answer, "y") == 0)
    {
        main();
    }
    else if (strcmp(answer, "n") == 0)
    {
        continue;
    }
    else 
    {
        printf ("\nERROR: Invalid input was provided. Your answer must be either y or n. Hit Enter to continue.");
        F = getchar();
        while ((getchar()) != F && EOF != '\n');
    }
}

我有其他与此类似的循环,按预期工作,但使用浮点数。所以我假设问题是我在这里使用char。现在发生的事情是它甚至没有提示用户提出问题。它只是询问问题并在之后显示错误。我确定这段代码还有其他问题,但由于我无法提示工作,我还无法测试其余部分。

4 个答案:

答案 0 :(得分:3)

我建议使用轻量级getchar()而不是重scanf

#include <stdio.h>

int c;  /* Note getchar returns int because it must handle EOF as well. */   

for (;;) {
    printf ("Enter y or n\n");
    c = getchar();
    switch (c) {
    case 'y': ...
        break;
    case 'n': ...
        break:
    case EOF:
        exit(0);
    }
}

答案 1 :(得分:1)

  • "a"是字符串文字== char id[2]={'a','\0'} //Strings are char arrays terminated by zero, in C
  • 'a'是字面意思
  • strcmp只是“比较两个字符串中的每个字符,直到你点击'\ 0'”
  • scanf ("%c", ___);期望一个地址写入第二个 论点。 C中的函数不能修改它们的参数(它们不会 可以访问它们 - 它们获得自己的本地副本),除非它们有 内存地址。您需要将&answer放在那里。

Jens已基本回答了这个问题,您很可能希望使用getchar,以便轻松检测EOF。与scanf("%c",...)不同,getchar不会跳过空格,我相信两个版本都会在每个版本之后留下未处理的输入行的其余部分(至少是换行符('\n')){ {1}}。你可能想要像

这样的东西
getchar

一旦你读完了它的第一个字符,你就丢弃剩余的字符。 否则,下一个int dump; while((dump=getchar())!='\n' && dump!=EOF) {}; 将获得同一行的下一个未处理字符。 ('\ n'如果该行是一个字母)。

答案 2 :(得分:0)

这是一种方法。它绝不是唯一的方法,但我认为它可以实现你想要的。你不应该递归地调用main函数。

#include <stdio.h>
#include <stdlib.h>

void run_program()
{
    printf("program was run.");
}

int main() {
    char answer[2] = "y\0";
    int dump;    

    do {

        if (answer[0] == 'y')
        {
            run_program(); /* Not main, don't call main recursively. */
        }

        printf ("\n\nWould you like to run the program again? Type y or n. Then, hit Enter.\n");
        scanf ("%1s", answer);

        /* Dump all other characters on the input buffer to
           prevent continuous reading old characters if a user
           types more than one, as suggested by ThorX89. */
        while((dump=getchar())!='\n' && dump!=EOF); 

        if (answer[0] != 'n' && answer[0] != 'y')
        {
            printf ("Please enter either y or n\n");
        }

    } while (answer[0] != 'n');

    return 0;
}

使用%s而不是%c,读入新行,以便新行字符不在stdin缓冲区中,这将成为下一次调用scanf时的答案。

run_program函数只是放置程序逻辑的函数。你可以随意调用它。我这样做是为了将菜单逻辑与实际程序的逻辑分开。

答案 3 :(得分:-1)

嗯,你正在比较两个字符串而不是字符。 如果要比较两个字符,则必须遵循以下语法:

char c;
scanf("%c",&c);

if(c == 'y')
    //do something
else
    //do nothing
相关问题