首页 > 解决方案 > 出于某种原因跳过代码的整个获取部分

问题描述

我想要做的是使用 C 替换 txt 文件中的特定行,但出于某种原因,在说出我想要更改的行之后,它刚刚结束了 exe。

void UpdateCustomerPortfolio()
{
    const char path[500] = "C:\\Users\\jason\\Desktop\\College stuff\\Final assessment\\Fundimentals of programming\\Accounts\\";
    int Ic[12],line;
    char txt[5] =".txt",num[100];
    FILE * fPtr;
    FILE * fTemp;
    char buffer[BUFFER_SIZE];
    char newline[BUFFER_SIZE];
    int count;
    
    fflush(stdin);
    
    printf("Input IC number: ");
    gets(Ic);
    
    strcat (path, Ic);
    strcat (path, txt);
    
    
    system("cls");
    
    printf("Enter the Information that requires an update:");
    printf("\n[01]First Name");
    printf("\n[02]Last Name");
    printf("\n[04]Home Address");
    printf("\n[05]Contact Number");
    printf("\n[06]Email Address\n");
    scanf("%d ",line);

由于某种原因,这是在用户输入他们想要更改的行后一直结束的部分。我确实尝试过使用 fflush(stdin); 又来了,但还是不行。

    printf("Replace '%d' line with: ", line);
    fgets(newline, BUFFER_SIZE, stdin);


    /*  Open all required files */
    fPtr  = fopen(path, "r");
    fTemp = fopen("replace.tmp", "w"); 

    /* fopen() return NULL if unable to open file in given mode. */
    if (fPtr == NULL || fTemp == NULL)
    {
        /* Unable to open file hence exit */
        printf("\nUnable to open file.\n");
        printf("Please check whether file exists and you have read/write privilege.\n");
        exit(EXIT_SUCCESS);
    }


    /*
     * Read line from source file and write to destination 
     * file after replacing given line.
     */
    count = 0;
    while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
    {
        count++;

        /* If current line is line to replace */
        if (count == line)
            fputs(newline, fTemp);
        else
            fputs(buffer, fTemp);
    }


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

    /* Delete original source file */
    remove(path);

    /* Rename temporary file as original file */
    rename("replace.tmp", path);

    printf("\nSuccessfully replaced '%d' line with '%s'.", line, newline);
}

标签: c

解决方案


你的 scanf 应该是scanf("%d", &line);


推荐阅读