【问题标题】:scanf won't designate char in c, and strcmp is messing with me [duplicate]scanf 不会在 c 中指定 char,而 strcmp 正在惹我 [重复]
【发布时间】:2018-01-08 13:14:13
【问题描述】:

这是一个项目中的一小部分,我正在尝试向用户询问一个字符。

void listBeer(int noRows) {
int endlessLoop = 1;
char sortChoice;
system("cls");

while(endlessLoop == 1)
{
    printf("Do you want to sort by name(n) or by product number(p)?\n");
    scanf("%c", &sortChoice);
    printf("kossan hoppade!\n");
    if(strcmp(sortChoice, "n") == 0 || strcmp(sortChoice, "N") == 0|| strcmp(sortChoice, "p") == 0 || strcmp(sortChoice, "P") == 0 ) {endlessLoop = 0;}
    else {printf("Please answer with n/N for name sorting or p/P\n");}
}

在比较过程中控制台崩溃,错误代码是“strcmp make pointer from integer without a cast”。

我尝试改用“char* sortchoice”,但是我的 scanf 不会做任何事情,并且在让我输入 char 之前,循环会通过两次。

我猜我要解决的问题不止一个,我确实尝试过将解决方案组合在一起,但对我来说仍然没有任何意义。

感谢任何解释!

【问题讨论】:

标签: c while-loop scanf


【解决方案1】:

不要使用strcmp(),而是使用sortChoice == 'n' 之类的简单比较。

strcmp() 不适用于比较单个字符。

【讨论】:

  • 谢谢!这消除了我所有的错误,但在让我输入任何内容之前,循环仍然经过两次。
  • 尝试在%c 之前添加一个空格,例如scanf(" %c", &sortChoice);。这会在某些环境中从缓冲区中删除过去的按键操作。
猜你喜欢
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多