Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.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语言中从文件中读取动态分配的未知长度字符串(必须防止从文件中读取数字)_C_String_File_Pointers_Dynamic Memory Allocation - Fatal编程技术网

在C语言中从文件中读取动态分配的未知长度字符串(必须防止从文件中读取数字)

在C语言中从文件中读取动态分配的未知长度字符串(必须防止从文件中读取数字),c,string,file,pointers,dynamic-memory-allocation,C,String,File,Pointers,Dynamic Memory Allocation,我的问题是,我需要从文件中读取字符串。文件示例: 例1句子 示例句子编号xd 595 xd 49 lol 但是我必须只读字符串部分,而不是数字。我想我必须将fscanf()与%s结合使用,但请告诉我你们对此的看法。 我的问题开始于如何使用malloc(),realloc()读取字符串(长度未知)?我自己尝试过,但失败了(我的解决方案在我的帖子底部)。 然后我需要在屏幕上显示结果 另外,我必须使用malloc()/calloc(),realloc()对于您的代码,您需要改进: fgetc返回int

我的问题是,我需要从文件中读取字符串。文件示例:

例1句子

示例句子编号xd 595 xd 49 lol

但是我必须只读字符串部分,而不是数字。我想我必须将
fscanf()
%s
结合使用,但请告诉我你们对此的看法。 我的问题开始于如何使用
malloc()
realloc()
读取字符串(长度未知)?我自己尝试过,但失败了(我的解决方案在我的帖子底部)。 然后我需要在屏幕上显示结果


另外,我必须使用
malloc()/calloc()
realloc()
对于您的代码,您需要改进:

  • fgetc
    返回
    int
    类型not
    char
    。因此,将
    char ch
    更改为
    int ch
  • 由于@pmg的注释使用EOF(可以是任何负值)而不是-1`
  • strcpy(word,ch)
    您尝试将字符(
    ch
    )复制到字符指针(
    word
  • 不要强制转换
    malloc
    realloc
    函数:
  • 为了解决您的问题,我建议您使用
    strtok
    函数按空格字符分割字符串,然后测试每个单词是否为数字。如果单词不是数字,可以使用
    strcat
    将单词连接到旧句子

    完整代码:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int is_number(char *str) {
        if (strlen(str) == 0)
           return -1;
        for(int i =0; (i < strlen(str)) && (str[i] != '\n') ; i++) {
            if(!isdigit(str[i]))
                return -1;
        }
        return 1;
    }
    
    int main()
    {
        FILE *fp = fopen("input.txt", "r");
        char line[256];
    
        if(!fp) return -1;
        char **sentence;
        int i = 0;
        sentence = malloc(sizeof(char *));
        if(!sentence) return -1;
        while(fgets(line, 256, fp)) {
            char * token = strtok(line, " ");
            size_t len = 0;
            sentence = realloc(sentence, sizeof(char *) * (i+1));
            if(!sentence) return -1;
            while(token != NULL) {
                if (is_number(token) != 1) {
    
                    sentence[i] = realloc(sentence[i], len + 2 + strlen(token)); // +2 because 1 for null character and 1 for space character
                    if (!sentence[i]) {
                        printf("cannot realloc\n");
                        return -1;
                    }
                    strcat(strcat(sentence[i], " "), token);
                    len = strlen(sentence[i]);
                }
                token = strtok(NULL, " ");
            }
            if(len > 0)
               i++;
        }
    
        for(int j = 0; j < i; j++) {
            printf("line[%d]: %s", j, sentence[j]);
        }
    
        for(int j = 0; j < i; j++) {
            free(sentence[j]);
        }
        free(sentence);
        fclose(fp);
        return 0;
    }
    
    

    对于您的代码,您有一些需要改进的地方:

  • fgetc
    返回
    int
    类型not
    char
    。因此,将
    char ch
    更改为
    int ch
  • 由于@pmg的注释使用EOF(可以是任何负值)而不是-1`
  • strcpy(word,ch)
    您尝试将字符(
    ch
    )复制到字符指针(
    word
  • 不要强制转换
    malloc
    realloc
    函数:
  • 为了解决您的问题,我建议您使用
    strtok
    函数按空格字符分割字符串,然后测试每个单词是否为数字。如果单词不是数字,可以使用
    strcat
    将单词连接到旧句子

    完整代码:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int is_number(char *str) {
        if (strlen(str) == 0)
           return -1;
        for(int i =0; (i < strlen(str)) && (str[i] != '\n') ; i++) {
            if(!isdigit(str[i]))
                return -1;
        }
        return 1;
    }
    
    int main()
    {
        FILE *fp = fopen("input.txt", "r");
        char line[256];
    
        if(!fp) return -1;
        char **sentence;
        int i = 0;
        sentence = malloc(sizeof(char *));
        if(!sentence) return -1;
        while(fgets(line, 256, fp)) {
            char * token = strtok(line, " ");
            size_t len = 0;
            sentence = realloc(sentence, sizeof(char *) * (i+1));
            if(!sentence) return -1;
            while(token != NULL) {
                if (is_number(token) != 1) {
    
                    sentence[i] = realloc(sentence[i], len + 2 + strlen(token)); // +2 because 1 for null character and 1 for space character
                    if (!sentence[i]) {
                        printf("cannot realloc\n");
                        return -1;
                    }
                    strcat(strcat(sentence[i], " "), token);
                    len = strlen(sentence[i]);
                }
                token = strtok(NULL, " ");
            }
            if(len > 0)
               i++;
        }
    
        for(int j = 0; j < i; j++) {
            printf("line[%d]: %s", j, sentence[j]);
        }
    
        for(int j = 0; j < i; j++) {
            free(sentence[j]);
        }
        free(sentence);
        fclose(fp);
        return 0;
    }
    
    

    无关建议:使用
    EOF
    (可以是任何负值)而不是
    -1
    char ch:
    ==>
    int ch无关建议:使用
    EOF
    (可以是任何负值)而不是
    -1
    char ch:
    ==>
    int ch我将在晚上测试它并给您反馈。不管怎样,你的解决方案似乎legit@Cris正如你在我的回答中看到的,我已经用你的输入测试了它。我的答案中的输出是您想要的:“cannot realloc”总是出现。你知道为什么会这样吗?@Cris你把我的代码复制粘贴正确了吗?它使用在线编译器工作,在我的电脑上也能工作。试着复制和粘贴代码。我会在晚上测试它并给你反馈。不管怎样,你的解决方案似乎legit@Cris正如你在我的回答中看到的,我已经用你的输入测试了它。我的答案中的输出是您想要的:“cannot realloc”总是出现。你知道为什么会这样吗?@Cris你把我的代码复制粘贴正确了吗?它通过使用在线编译器工作,在我的电脑上也能工作。试着复制和粘贴代码。
    
    $cat input.txt
    Example 1 sentence
    Example sentence number xd 595 xd 49 lol
    
    ./test
    
    line[0]:  Example sentence                                                                                                                                  
    line[1]:  Example sentence number xd xd lol