【问题标题】:while loop != string C [duplicate]while循环!=字符串C [重复]
【发布时间】:2014-11-28 20:06:53
【问题描述】:

这个程序快完成了。唯一的问题是当用户输入退出退出时,它应该关闭程序。但它没有,它一直在重复。我知道如果我使用单个字符(例如'q')它会起作用,因为我已经尝试过了。但我希望程序检测到用户输入了字符串“quit”。你能帮我解决这个问题吗?非常感谢!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "sales.txt"

int main()
{
   char firstName[41];
   char itemSold[41];
   FILE *salesFile;

   salesFile = fopen(FILENAME, "w");

   if( salesFile == NULL )
   {
       printf("Error opening file\n");
       return 1;
   }

   printf("Please enter first name and item sold\n");
   printf("Please quit quit to end\n");
   printf("> ");
   scanf("%40s %40s", firstName, itemSold);

   while(firstName != "quit" && itemSold != "quit")
   {
       fprintf(salesFile, "%s %s\n", firstName, itemSold);
       printf("> ");
       scanf("%40s %40s", firstName, itemSold);
   }

   fclose(salesFile);

   return 0;


}

【问题讨论】:

  • 使用 strcmp 代替相等运算符
  • while(stcmp(first, second) != 0)

标签: c string while-loop


【解决方案1】:

你比较的字符串不是:

firstName == "quit"
firstName != "quit"

(仅比较其中的 地址),但与:

strcmp (firstName, "quit") == 0
strcmp (firstName, "quit") != 0

比较内容。

【讨论】:

  • 太棒了!它起作用了,现在我明白了。我很困惑,因为我不希望它等于 0,而是实际上不等于。但我成功了,非常感谢!
猜你喜欢
  • 2017-01-20
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 2014-09-25
  • 2011-06-18
  • 2022-01-05
相关资源
最近更新 更多