c - C 中的 while 循环条件错误的原型(prototype)函数

标签 c while-loop

如何使用 while 循环条件运行我自己的原型(prototype)函数?

#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!")) ) ”?
首先:糟糕的编码风格。这是 if/else 的简短版本。如果第一个条件为真,则返回 ? 之后的值否则返回以下值:

为什么返回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");
    }
  }
}

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

关于c - C 中的 while 循环条件错误的原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19707097/

相关文章:

java - 方法返回 false,但条件匹配并且应该返回 true

php - 我的 MySQL 查询、while 循环和 SESSIONS 无法正常工作 PHP

c - 为什么即使值为真,我的 while 循环也会继续执行?

c - 通过递归的幂函数

javascript - 来自 C ASM 的 NodeJS 按位运算符

c++ - 使用 Arduino 和 C++ 声明和写入数组的问题

php - 如何从不同表复制列的值(SQL)

c - 链接器是否用于简单的 C 程序?

c - 为什么在递归函数中修剪字符串时会出现段错误?

JAVA,Switch case需要两个条目才能工作