Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何使do-while循环正常工作?_C_Loops_Do While - Fatal编程技术网

C 如何使do-while循环正常工作?

C 如何使do-while循环正常工作?,c,loops,do-while,C,Loops,Do While,在此代码中,第二个do while循环工作不正常。每当我按y再次输入时。它只是一次又一次地重复输入[y/n]选项,而不是从第二个do while循环开始。我不想让它给我一个选项,输入身份证号码一次又一次 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *fr = fopen("file.csv", "r")

在此代码中,第二个
do while
循环工作不正常。每当我按
y
再次输入时。它只是一次又一次地重复输入[y/n]选项,而不是从第二个
do while循环开始。我不想让它给我一个选项,输入身份证号码一次又一次

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

int main() {
    FILE *fr = fopen("file.csv", "r");
    char string[200], toFind[200], opt;
    int err = 0;
    char *line1 = NULL;

    do {
        printf("Enter ID Card number: ");
        scanf("%s", toFind);
        if (strlen(toFind) != 13) {
            break;
        }

        do {     // This loop is not working properly
            {
                err = 1;
                while (fgets(string, 200, fr)) {
                    line1 = strtok(string, "\n");
                    printf("%s\n", line1);
                    err = 0;
                }
            }
            printf("Repeat again [y/n]: ");
            scanf("%s", &opt); 
        } while (opt == 'y');
    } while(err);

    return 0;
}
#包括
#包括
#包括
int main(){
FILE*fr=fopen(“FILE.csv”、“r”);
字符字符串[200],toFind[200],opt;
int err=0;
char*line1=NULL;
做{
printf(“输入身份证号码:”);
扫描频率(“%s”,toFind);
如果(strlen(toFind)!=13){
打破
}
do{//此循环工作不正常
{
误差=1;
while(fgets(string,200,fr)){
line1=strtok(字符串“\n”);
printf(“%s\n”,第1行);
误差=0;
}
}
printf(“再次重复[y/n]:”;
scanf(“%s”和&opt);
}while(opt='y');
}而(错),;
返回0;
}

首先,您不能使用
%s
指令将输入读取到单个
字符中。这是用于读取非空字符串输入,因此它将始终存储至少两个字符,最后一个是字符串终止符。单个
char
没有空间容纳该字符,因此您的程序具有未定义的行为。您可以改为使用
%c
,但请注意,后者是少数不会导致跳过前导空格的字段指令之一

每当我再次按y键进入时。它只是一次又一次地重复输入[y/n]选项,而不是从第二个do while循环开始

即使我们假设覆盖变量
opt
的边界没有明显的效果,您也错了:当循环循环到新的迭代时,它会在循环体的开始处再次开始

但是当它到达那里时,它会做什么呢?首先,为了达到<代码> SCANF,程序必须首先到达并通过<代码>(FGET(String,200,FR))< /Cult>循环。循环体中没有
goto
break
,因此只有当
fgets()
返回空指针时,它才会终止,这表明它已到达文件末尾(很可能)或遇到I/O错误。当控制循环回到该循环时,文件
fr
没有任何变化。它仍然位于文件的末尾(或者仍然处于错误状态),因此有充分的理由期望下一个
fgets()
将再次返回空指针,这样循环的主体就不会执行一次


也许您想在
fgets()
循环之前
倒带(fr)
,这样您就可以再次读取该文件,但我不清楚该循环的要点,因此我不确定这是否真的有意义。

scanf(“%s”,&opt);-未定义的行为,因为%s希望指向字符数组的指针足够长,以容纳我不理解的字符串。然后,您需要先阅读一本C语言书