c - 如何使 if 语句打印需要结果?
问题描述
这段代码有一个问题。问题出在
if语句中的问题
if(all_digits(to_find) && strlen(to_find) == 13)
每当我输入 13 个字符但不是从文件中输入时,它就会给我一条 else 语句的消息,但Found. Hello World!
也会打印。虽然Found. Hello World!
在 if 语句中。它不应该被打印。如何使 if 语句正常工作?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int all_digits(char *s){
for (; *s!=0; s++){
if (!isdigit(*s)){
return 0;
}
}
return 1;
}
另一部分代码
int main(){
FILE * fr = fopen("file.csv", "r");
char save[500], line[200], to_find[50];
int oneByOne = 0, numberOfFields=8;
char *word = NULL;
printf("Enter the ID card number: ");
scanf("%s", to_find);
if(all_digits(to_find) && strlen(to_find) == 13){
while(fgets(line, 200, fr)){
word = strtok(line, "\n");
strcpy(save, line);
if (strstr(save, to_find)){
char *wordone = strtok(save, ",");
while (wordone != NULL){
printf("Here are your details: %s\n", wordone);
wordone = strtok(NULL, ",");
}
}
}
fclose(fr);
printf("Found. Hello World!\n");
}
else {
printf("enter correclty\n");
}
return 0;
}
解决方案
要在没有级联 if-then 的情况下运行多个测试,您可以使用错误标志和一次性循环,如下所示:
int err = 0; /* Be optimistic! (0 indicates success) */
do {
if (!test1-passed) {
err = 1;
break;
}
if (!test2-passed) {
err = 2;
break;
}
...
if (!testN-passed) {
err = N;
break;
}
printf("Success! All tests passed");
} while (0);
if (err) {
printf("Test %d failed", err);
}
应用于您的特定问题,代码可能如下所示
... /* definitions here */
int err = 0; /* Be optimistic! (0 indicates success) */
do {
... /* input here */
do {
if (!all_digits(to_find)) {
err = 1;
break;
}
if (strlen(to_find) != 13) {
err = 2;
break;
}
{
err = 3 /* be pessimistic! */
while(fgets(line, 200, fr)){
/* word = strtok(line, "\n"); */ /* word is not needed. */
strcpy(save, line); /* Introducing save here is not necessary,
all following operation can be applied to line. */
if (strstr(save, to_find)){
char *wordone = strtok(save, ",");
while (wordone != NULL){
printf("Here are your details: %s\n", wordone);
wordone = strtok(NULL, ",");
err = 0; /* Phew, we are lucky! */
}
}
}
if (err) {
break;
}
}
printf("Success! All tests passed");
} while (0);
if (err) {
printf("Test %d failed", err);
}
} while (err);
推荐阅读
- android - 无法安装应用程序:SHELL_UNRESPONSIVE -android studio 3.5
- mongodb - 带有排序内部字段的 Mongo 查询返回的结果少于集合中的结果
- c# - 如何隐藏数据表中的特定数据行而不删除它?
- laravel - 结合表单中的三个字段并在 Laravel 5.5 中使用两个字段验证表中的唯一性
- ruby-on-rails - 可以使用 Monkey Patch Object 类创建自定义数据格式化程序吗?
- c++ - 用数组添加 2 个大整数
- javascript - 如何在异步函数中处理多个等待
- android - 使用 Onesignal 在 android 中打开应用程序时如何显示自定义通知对话框
- reporting-services - 如果选择了多个参数值,如何显示“多个”或显示选择的单个值
- regex - 正则表达式在 python 中验证代理 uri