无法在c中动态分配的字符串中输入

时间:2016-03-03 08:37:05

标签: c string memory input

我一直在用C编写一个HTML生成器。经过一些研究,我发现了一些代码,它允许我在一个数组中获取输入,如果你需要它可以为它分配更多的内存。问题是,经过几次,代码停止工作。

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

char *inputString(FILE *fp, size_t size);

int main(){
    char *nameOfFile;
    char *multiF;
    int choice;
    FILE *f;
    printf("Name of file: ");
    nameOfFile=inputString(stdin, 10);
    f = fopen(strcat(nameOfFile,".html"),"w+");
    fprintf(f, "<head>\n");
    printf("Title: ");
    multiF=inputString(stdin, 10);
    fprintf(f, "\t<title>%s</title>\n</head>\n<body>\n", multiF);
    while(choice != 99){ //Code stops working in while loop
        printf("What do you want to do?\n");
        printf("[1]Headings\n");
        printf("[2]Paragraphs\n");
        printf("[99]Exit\n");
        scanf("%d",&choice);
        switch(choice){
            case 1:
                printf("What size[1-6]? ");
                scanf("%d",&choice);
                if(choice < 7 && choice > 0){
                    printf("Heading[%d]:",choice);
                    multiF=inputString(stdin,10);
                    fprintf(f,"<h%d>%s</h%d>",choice,multiF,choice);
                }else{
                    printf("Input something useful...\n");
                }
                break;
            case 2:
                printf("Paragraph: ");
                multiF=inputString(stdin,10);
                fprintf(f,"<p>%s</p>",multiF);
                break;
            case 99:
                break;
            default:
                printf("Input something useful...\n");
        }
    }
    fprintf(f,"</body>");
    free(multiF);
    free(nameOfFile);
    return 0;
}

char *inputString(FILE *fp, size_t size){
    char *str;
    int ch;
    size_t len=0;
    str = realloc(NULL, sizeof(char)*size);
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

1 个答案:

答案 0 :(得分:0)

这应该有效:

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

void inputString(char **str, FILE *fp); // No char *str, because we need to change the value of pointer str

int main(){
    char *nameOfFile = malloc(0);
    char *multiF = malloc(0); // Calling malloc() for later free()
    int choice = 0; // Initialization
    FILE *f;
    printf("Name of file: ");
    inputString(&nameOfFile, stdin);
    nameOfFile = realloc(nameOfFile, strlen(nameOfFile) + 5); // You need more memory for ".html"
    strcat(nameOfFile, ".html");
    f = fopen(nameOfFile, "w");
    fprintf(f, "<head>\n");
    printf("Title: ");
    inputString(&multiF, stdin);
    fprintf(f, "\t<title>%s</title>\n</head>\n<body>\n", multiF);
    while(choice != 99){
        printf("What do you want to do?\n");
        printf("[1]Headings\n");
        printf("[2]Paragraphs\n");
        printf("[99]Exit\n");
        scanf(" %d%*c", &choice); // " %d" to discard whitespace characters, and "%*c" to consume '\n'
        switch(choice){
            case 1:
                printf("What size[1-6]? ");
                scanf(" %d%*c", &choice);
                if(choice < 7 && choice > 0){
                    printf("Heading[%d]:", choice);
                    inputString(&multiF, stdin);
                    fprintf(f, "<h%d>%s</h%d>", choice, multiF, choice);
                }else{
                    printf("Input something useful...\n");
                }
                break;
            case 2:
                printf("Paragraph: ");
                inputString(&multiF, stdin);
                fprintf(f, "<p>%s</p>", multiF);
                break;
            case 99:
                break;
            default:
                printf("Input something useful...\n");
                break;
        }
    }
    fprintf(f, "</body>");
    free(multiF);
    free(nameOfFile);
    fclose(f); // Don't forget to close the file
    return 0;
}

void inputString(char **str, FILE *fp){
    int ch;
    size_t size = 1, index = 0;
    free(*str);
    *str = malloc(size);
    if(!*str)
        return;
    while(EOF != (ch = fgetc(fp)) && ch != '\n'){
        (*str)[index++] = ch;
        if(index == size){
            *str = realloc(*str, size += 16); // sizeof (char) is guaranteed to be 1 by the standard
            if(!*str)
                return;
        }
    }
    (*str)[index] = '\0'; // No need to increase index
}

请参阅我的评论以获取详细信息。

您的代码中存在一些问题:

  1. scanf("%d",&choice);后,&#39; \ n&#39;将留在stdin。当inputStrng()满足时,该函数会立即停止生成字符串。
  2. 要更改函数中指针变量的值,需要将指针传递给指针,例如char **str
  3. 您忘记关闭文件,这可能会导致信息丢失。