【问题标题】:Yes no string in C [duplicate]是的,C 中没有字符串 [重复]
【发布时间】:2018-02-19 02:42:57
【问题描述】:

我搜索了论坛,但似乎找不到适合我特定问题的答案(我也尝试过 Google)。我似乎在正确比较字符串(“是”、“是”、“否”、“否”)时遇到问题。我最初尝试了 if else ,但我认为 while 循环更有效。有什么建议?

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

double far = 0;
double cel = 0;
double userValue = 0;
double endResult = 0;
int choice;
char *decision = "";


int main() 
{  
 conversion();
 return 0;   
}

conversion() {
   printf("Please enter a 1 for Celsius to Fahrenheit conversion OR\n a 2 
   for 
   Fahrenheit to Celsius conversion\n");

scanf("%d", &choice);

   if(choice == 1) {
     printf("Please enter a value for Celsius.  Example 32 or 32.6\n");
     scanf("%lf", &userValue);
     endResult = (userValue * (9.0/5.0) + 32);
     printf("%lf\n", endResult);
     yesOrNo();
} 

else 

printf("Please enter a value for Fahrenheit.  Example 212 or 212.6\n");
scanf("%lf", &userValue);
endResult = (userValue -32) * (5.0/9.0);
printf("%lf\n", endResult);
yesOrNo();

}


yesOrNo() {

printf("Do you want to continue?    Enter Yes or No\n");
scanf(" %s", &decision);   

 while(decision == "Yes" || decision == "yes") {

    conversion();

 }

 exit(0);

}

【问题讨论】:

  • 不要对字符串使用 == 比较器,而是使用 stricmp
  • 你需要使用strcmp来比较字符串的内容,否则你只是比较它们是否在同一个地址。
  • 请注意,您将在每次转换时进行递归:main() 调用转换(),转换调用 yesOrNo(),yesOrNo() 调用转换,等等。您冒着堆栈溢出异常的风险。
  • char *decision = "";...scanf(" %s", &amp;decision);——这是错误的。 decision 是一个指向空字符串的指针。您需要一个数组来保存用户输入,例如char decision[100];。然后使用scanf("%99s", decision); 获取用户输入。

标签: c string while-loop


【解决方案1】:

C 没有字符串。您必须使用函数 strcmp() 来比较字符串文字和/或以 null 结尾的字符数组。

decision == "Yes" 

应该是

strcmp(decision,"Yes") == 0

【讨论】:

  • 我在发布后不久就发现了问题。事实上,我什至无法在它关闭之前提交我的回复。
【解决方案2】:

您不能使用== 运算符比较字符串文字,您需要使用不区分大小写的strcasecmp()() 或stricmp() 函数。
如果字符串相等 strcasecmp()stricmp() 返回 0,如果第一个参数大于第二个参数,则返回 正数 否则返回 负数

【讨论】:

  • stricmp 在这个事件中
  • POSIX 不区分大小写的字符串比较函数是strcasecmp(),在&lt;strings.h&gt;,IIRC 中声明
  • @Jonathan Leffler,你刚刚检查对了,非常感谢!!
  • You can't compare string literals using == 是不是文字都没有关系。您当然也可以使用== 比较它们,但您比较的是指针而不是它们引用的对象
  • @ PeterJ_01,是的,完全同意,我的意思是使用== 运算符不会得到预期的结果,即比较字符串,谢谢评论!!
猜你喜欢
  • 1970-01-01
  • 2021-01-14
  • 2023-03-31
  • 2013-01-15
  • 2022-01-17
  • 2018-11-25
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
相关资源
最近更新 更多