gpt4 book ai didi

c - 如何根据用户在 C 中的输入停止程序

转载 作者:太空宇宙 更新时间:2023-11-04 00:25:09 25 4
gpt4 key购买 nike

我刚开始学习 C,我在根据用户输入的内容停止我的程序时遇到了问题。

#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
scanf_s(" %d %d %s", &a, &b, &c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}

我遇到的问题是必须在我的 scanf_s 中放入另一个变量 c。我该怎么做才能让用户不必在 2 个数字后输入另一个词?另外我如何检查用户是否只输入“停止”以便它停止程序?顺便说一句,当我执行“10 10 停止”时,我现在拥有的方式也不会停止程序。谢谢。

最佳答案

  1. 删除 & for c in scanf_s("%d %d %s", &a, &b, &c);
  2. 使用 strcmp 比较字符串。
  3. 如果您在比较时需要忽略大小写,请使用 strcasecmp(对于基于 UNIX 的系统)和 stricmp(对于 Windows)。
  4. 如果您需要至少运行一次循环,请使用 do-while 而不是 while。

完整的工作代码:

#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};

do {
printf("Enter the two values you like to compare, type stop to end.\n");
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
while (strcmp(c,"stop"));
printf("Thanks for playing.");
getchar();
return 0;
}

关于c - 如何根据用户在 C 中的输入停止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20738324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com