首页 > 解决方案 > 虽然循环在C中被跳过

问题描述

这是我的代码,我想显示存储在文本文件中的所有行,同时通过从用户那里获取要替换的行的输入来替换该特定行。

///Get Customer ID
char c_id[100];
printf("Enter Customer ID: ");
scanf("%s", &c_id);

FILE* fPtr;
FILE* fTemp;
char temp_line[100];
char buffer[100];
char newline[100];
int i, arr_n, line, count;

/* Remove extra new line character from stdin */
fflush(stdin);
fflush(stdout);

/// Open all required files
fPtr = fopen(c_id, "r");
fTemp = fopen("replace.txt", "w");

/// Print the content
i = 1;
arr_n = 0;

printf("\nOptions:\n");

while (fgets(buffer, BUFFER_SIZE, fPtr))
{
    printf("%d. %s\n", i, buffer);
    i = i + 1;
}

printf("Enter your options: ");
scanf("%d", &line);

printf("Enter the updated information: ");
scanf("%s", &newline);

count = 0;

while (fgets(temp_line, BUFFER_SIZE, fPtr))
{
    count++;
    if (count == line)
    {
        switch (line)
        {
        case 1:
            fprintf(fTemp, "Name: %s", newline);
            break;
        case 2:
            fprintf(fTemp, "Date of birth: %s", newline);
            break;
        case 3:
            printf("It did got here");
            fprintf(fTemp, "Address: %s", newline);
            break;
        case 4:
            fprintf(fTemp, "Contact 1: %s", newline);
            break;
        case 5:
            fprintf(fTemp, "Contact 2: %s", newline);
            break;
        default:
            printf("Invalid answer given");
        }
    }
    else
    {
        fputs(temp_line, fTemp);
    }
}

/// Close all files to release resource
fclose(fPtr);
fclose(fTemp);


/// Delete original source file 
remove(c_id);

/// Rename temporary file as original file 
rename("replace.txt", c_id);

printf("\nSuccessfully updated the information");

这是最后一个while被跳过的循环。为什么它会跳过那个while循环,我似乎找不到它跳过的原因。我尝试将temp_line更改为另一个缓冲区,它仍然是一样的。

我尝试先删除一些与它无关的不必要行并尝试解决问题,但仍然找不到 while 循环被跳过的确切原因。

是因为开关盒吗?

还是缓冲区有问题?

标签: c

解决方案


您的第一个循环到达文件末尾。fgets如果到达文件末尾,函数返回指向缓冲区的指针或空指针。由于您在循环中将指针值用作布尔值,因此while跳过第二个循环,因为您的文件已经用尽并fgets返回 NULL。 while(NULL) { ... }永远不会进入 while 循环代码块。

使用函数fseekrewind在第二个循环之前将文件指针重置到文件顶部。


推荐阅读