首页 > 解决方案 > 我们可以用字符串停止 while 函数吗?

问题描述

我是编程的业余爱好者,我正在尝试我在学习时感兴趣的东西。所以我想看看我是否可以“检查”用户输入了我想要继续使用该程序的单词,但我似乎无法找到答案。

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

void digit_check( float n )
{
    printf("Please enter a number:");
    scanf("%f",&n);
    printf("\n");
    if(n >= 10 && n < 100)
    {
        printf("The number you entered is 2 digit.\n");
    }
    else if(n < 10)
    {
        printf("The number you entered is 1 digit.\n");
    }
    else
    {
        printf("The number you entered is more than 2 digit.\n");
    }
}
int main()
{
float n;
char answer[5];
char str1[5];
int cmp = 1;
while(cmp = 1)
{
   printf("Do you want to continue?");
   scanf("%s",answer);
   strcpy(str1, "Yes");
   cmp = strcmp(answer,str1);
   if(cmp = 1)
   {
      digit_check(n);
   }
}
return 0;
}

标签: c

解决方案


当两个字符串相等时,strcmp 返回 0,并将其与 1 进行比较。

cmp = strcmp(answer,str1);
if(cmp = 1)

此外,声明

   if(cmp = 1)

正在将值 1 分配给 cmp 变量。

正确的条件应该是

       if(cmp == 0)

例如,使用==(双 '=' 符号)来检查相等性,而不是使用单个 '=' 符号来进行赋值。


推荐阅读