检查 char 变量的内容 - C 编程

Pau*_*ris 3 c variables if-statement char

这似乎是一个非常简单的问题,但我正在努力解决它。我使用 Objective C 编写 iPhone 应用程序已经有几个月了,但我决定学习 C 编程,以便为自己打下更好的基础。

在 Objective-C 中,如果我有一个名为“label1”的 UILabel,其中包含一些文本,并且我想根据该文本运行一些指令,那么它可能是这样的;

if (label1.text == @"Hello, World!")
{
NSLog(@"This statement is true");
}
else {
NSLog(@"Uh Oh, an error has occurred");
}
Run Code Online (Sandbox Code Playgroud)

我写了一个非常简单的 C 程序,它用来printf()请求一些输入,然后用来scanf()接受来自用户的一些输入,所以像这样;

int main()
{
    char[3] decision;

    Printf("Hi, welcome to the introduction program.  Are you ready to answer some questions? (Answer yes or no)");
    scanf("%s", &decision);
}
Run Code Online (Sandbox Code Playgroud)

我想做的是应用一个if声明来说明如果用户输入“是”则继续提出更多问题,否则打印出一行文字表示感谢。

使用 scanf() 函数后,我捕获用户输入并将其分配给变量“决策”,以便现在应该等于是或否。所以我想我可以做这样的事情;

if (decision == yes)
{
     printf("Ok, let's continue with the questions");
}
else 
{
     printf("Ok, thank you for your time.  Have a nice day.");
}
Run Code Online (Sandbox Code Playgroud)

这会出现“使用未声明的标识符是”的错误。我也尝试过;

if (decision == "yes")
Run Code Online (Sandbox Code Playgroud)

这会导致“与字符串文字的比较结果未指定”

我尝试通过计算所输入的字符数来查看它是否有效;

if (decision > 3)
Run Code Online (Sandbox Code Playgroud)

但得到“指针和整数‘Char and int’之间的有序比较”

我也尝试过检查变量的大小,如果它大于 2 个字符,那么它一定是“是”;

if (sizeof (decision > 2))
Run Code Online (Sandbox Code Playgroud)

我很感激这可能是我忽略的简单或琐碎的事情,但任何帮助都会很棒,谢谢。

Dav*_*rtz 5

丹尼尔·哈维夫的回答告诉你应该做什么。我想解释一下为什么你尝试的方法不起作用:

if (decision == yes)
Run Code Online (Sandbox Code Playgroud)

没有标识符“是”,因此这是不合法的。

if (decision == "yes")
Run Code Online (Sandbox Code Playgroud)

这里,“yes”是一个字符串文字,其计算结果是指向其第一个字符的指针。这将“决策”与指针进行了等价比较。如果它是合法的,那么如果它们都指向同一个地方,那就是真的,这不是你想要的。事实上,如果你这样做:

if ("yes" == "yes")
Run Code Online (Sandbox Code Playgroud)

该行为是未定义的。如果实现将相同的字符串文字折叠到相同的内存位置(它可能会或可能不会),它们都将指向相同的位置。所以这绝对不是你想要的。

if (sizeof (decision > 2))
Run Code Online (Sandbox Code Playgroud)

我假设你的意思是:

if( sizeof(decision) > 2 )
Run Code Online (Sandbox Code Playgroud)

“sizeof”运算符在编译时而不是运行时计算。而且它独立于存储的内容。sizeof Decision 为 3,因为您将其定义为容纳三个字符。所以这并没有测试任何有用的东西。

正如另一个答案中提到的,C 有 'strcmp' 运算符来比较两个字符串。如果您愿意,您还可以编写自己的代码来逐个字符地比较它们。C++ 有更好的方法来做到这一点,包括字符串类。

以下是您可以如何执行此操作的示例:

int StringCompare(const char *s1, const char *s2)
{ // returns 0 if the strings are equivalent, 1 if they're not
  while( (*s1!=0) && (*s2!=0) )
  { // loop until either string runs out
     if(*s1!=*s2) return 1; // check if they match
     s1++; // skip to next character
     s2++;
  }
  if( (*s1==0) && (*s2==0) ) // did both strings run out at the same length?
      return 0;
  return 1; // one is longer than the other
}
Run Code Online (Sandbox Code Playgroud)