这个程序快完成了。唯一的问题是,当用户输入 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/