如何使用 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/