繁体   English   中英

C语言中我的while循环条件错误的原型函数

[英]Prototype function with my while loop condition error in C

我如何在while循环条件下运行自己的原型函数?

#include <stdio.h>
#include <conio.h>
#include <string.h>

msghere(char *text){
    printf("%s",text);
    return 0;
}
void main(){
    char inp[256]={0};
    clrscr();
    while( strcmp(inp,"pass") && msghere("Error!")){
        memset(inp,0,strlen(inp));
        printf("Type \"pass\": ");
        gets(inp);
    }
    msghere("Right Answer!");
    getch();
}

该代码输出以下内容:

Error!Right Answer!

您想要的是一个do-while循环和类似if条件的东西。

int msghere(char *text){
    printf("%s",text);
    return 1;
}
int main(void)
{    
    do
    {
    //your code
    }while( (strcmp(inp, "pass") == 0 ? 0 : msghere("error!")) );
}

为什么要同时做?
因为您希望用户在第一次检查之前进行输入。 符合逻辑吗?

WTF是“ while( (strcmp(inp, "pass") == 0 ? 0 : msghere("error!")) ) ”?
首先:不良的编码风格。 如果/否则为简短版本。 如果第一个条件为true,则返回?之后的值。 否则返回以下值:

为什么返回1; 在msghere()中?
因为您的do while循环将评估是否存在错误。 错误== True->再做一次。

您应该做什么:
如下所示:

// your original msghere
int main(void)
{
  int passed = 0;  //false
  // some code
  while(!passed) //while not passed
  {
    //read input with fgets like said in the comments
    if(strcmp(inp, "pass") == 0)
    {
       passed = 1; // true
    }
    else
    {
      msghere("error");
    }
  }
}

它使用状态变量,并且更易于阅读。

#include <stdio.h>
#include <conio.h>
#include <string.h>

int msghere(const char *text)
{
    printf("%s",text);
    return 1; /* you want 1 instead of 0, because (strcmp != 0) && 1 == true */
}

int main(void)
{
    char inp[256];

    clrscr();
    do {
        printf("Type \"pass\": ");
        fgets(inp, sizeof inp, stdin); /* gets is deprecated, use fgets */
    } while (strcmp(inp, "pass\n") && msghere("Error!"));
    msghere("Right Answer!");
    getch();
    return 0;
}

编辑:

为什么在传递while((strcmp(inp, "pass\\n") && msghere("Error!"))之后有\\n while((strcmp(inp, "pass\\n") && msghere("Error!"))

因为fgets在字符串的末尾加上了\\n ,所以您可以使用以下命令跳过这一行:

if (fgets(inp, sizeof inp, stdin) != 0)
{
    size_t len = strlen(inp);

    if (len > 0 && inp[len - 1] == '\n')
        inp[len - 1] = '\0';
    /* ... */
}

似乎您使用的是Turbo C或旧的编译器,请使用现代的编译器(例如MinGW),此外:

  • 无需初始化inp
  • 无需在每次迭代中进行memset设置
  • 函数必须返回某种类型(在这种情况下为int )或void
  • const限定符将数据对象显式声明为无法更改的对象,请使用它来帮助编译器构建更好的代码。
  • 使用int main(void)代替void main()

如果发现string1(或其前n个字节)分别小于,匹配或大于string2,则strcmp()函数返回的整数小于,等于或大于零。

因此,您在while循环中对strcmp的调用返回非零值。因此,将评估下一个条件,即调用function(msghere) 该函数执行,打印结果并返回零,这使得在while循环中条件为假。

现在,您知道该怎么办了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM