gpt4 book ai didi

c - 如何读取特定字符串的标准输入并对它们执行 bool 运算?

转载 作者:行者123 更新时间:2023-11-30 15:07:28 25 4
gpt4 key购买 nike

我正在尝试从表单的标准输入读取文本文件

12  1 $2
30 3 $9
1 1 $5 asdf
0 23 $3
0 alpha
1 beta
2 gamma
3 delta

我希望第一个条件语句检查范围值并查看是否出现“alpha”、“beta”、“gamma”和“delta”。如果这些字符串之一不存在,那么我想使用 exit(1)。

我不太确定如何准确地将这些字符串存储在内存中或从标准输入中搜索它们。任何指导表示赞赏。

<小时/>
#include <stdio.h>
#include <stdlib.h>
int main(){
int x;
int y;
char type[3];

while(1){
if(scanf("%d %d %s%*[^\n]%*c", &x, &y, type)!=3)break;
if(x>30 || y>30 || x<0 || y<0)||!("alpha" && "beta"
&& "gamma" && "delta"))
// The above syntax is wrong, but I think it shows what I'm thinking.
// If one of those strings are not found, exit(1).
{
exit(1);
}
if(x==0 || y==0){
goto X;
}
//Do stuff
}
X:if((x==0 || y==0)==1){

//Do stuff
return(0);
}

}//end main

最佳答案

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

int main(void){
int x;
int y;
char type[3];
char kinds[16];
int alpha, beta, gamma, delta;//flags
int status;

alpha = beta = gamma = delta = 0;
while(1){
if((status = scanf("%d %d %2s", &x, &y, type)) == 3){
if(x > 30 || y > 30 || x < 0 || y < 0)
exit(1);
//valid data1
//do stuff
puts("valid data1");//debug print
} else if(status == 1){
if(1 == scanf("%15s", kinds)){
if(strcmp(kinds, "alpha")==0) alpha = 1;
else if(strcmp(kinds, "beta")==0) beta = 1;
else if(strcmp(kinds, "gamma")==0) gamma = 1;
else if(strcmp(kinds, "delta")==0) delta = 1;
//else /* unknown kind*/ ;
}
} else {
break;
}
scanf("%*[^\n]");scanf("%*c");//clear upto end of line
}
if(!(alpha && beta && gamma && delta)){
exit(1);
}
//valid data2
//do stuff
puts("valid data2");//debug print

return 0;
}

关于c - 如何读取特定字符串的标准输入并对它们执行 bool 运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38272097/

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