c - while 循环 != 字符串 C

标签 c string while-loop

这个程序快完成了。唯一的问题是,当用户输入 quit quit 时,它应该关闭程序。但事实并非如此,而且不断重复。我知道如果我使用单个字符(例如“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;


}

最佳答案

您比较的字符串不与:

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

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

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

比较内容。

关于c - while 循环 != 字符串 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27195279/

相关文章:

c - 变量周围的运行时检查失败堆栈已损坏

c++ - 需要将一行中的数字与字符串分开,在C++中用 ';'(25; 16; 67; 13)分隔

c - 如何在C中正确使用fopen命令?

c - return(NULL) 中多余括号的目的是什么

Java While 循环程序

Java正则表达式匹配元组

java - 表达式的类型必须是数组类型,但它解析为字符串

c++ - WINAPI URLDownloadToFileA 问题

c - 指向二维数组列的指针

javascript - 如何返回字符串中子串的出现频率?