gpt4 book ai didi

比较变量和字符串

转载 作者:行者123 更新时间:2023-11-30 15:06:19 27 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来启动 OS X El Capitan 上的特定功能。代码如下所示:

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

int main()
{
char mainchoice;
printf(">>> ");
scanf("%s", &mainchoice);
if (strcmp(&mainchoice, "start ftp") == 0) {
system("ftp");

}
else if (strcmp(&mainchoice, "start say") == 0) {
system("say hello");
}
else {
system("say Error")
}

}

这只是示例代码。

当我运行它时,它总是通过 say 命令提示错误。我做错了什么?

最佳答案

重点在这里:-

char mainchoice; //declared as a char

scanf("%s", &mainchoice); //using the %s placeholder which is for string

//for character it is %c

了解代码背后的逻辑是您想要输入字符串而不是字符。

创建一个字符数组,如下所示:-

char mainchoice[20]; //this can hold your string, one character at one index each of the array

因为,您在字符串比较中使用了多个单词(“start say”)

(strcmp(&mainchoice, "start say") == 0)

scanf 不适用于多字。一旦您提供空格、制表符、换行符,scanf 就会停止从键盘读取。

要解决该问题,请使用 fgets。这是阅读多个单词甚至整个句子的最佳方式。 永远不要使用 gets()!它很容易受到缓冲区溢出的影响!

fgets(mainchoice, 20, stdin);

关于比较变量和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184836/

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