首页 > 解决方案 > 我对 C 编程有点陌生。我需要帮助将文件(test.txt)中的字符串推送到不带逗号的数组中

问题描述

我试图通过 malloc(),free(),realloc() 从文件读取输入来解决动态内存分配问题;我只需要帮助将字符串从文件中推送到数组中,而不需要逗号。我的 test.txt 文件如下:

一,5,0

一,25,1

一,1,2

r,10,1,3

f,2

int i;

int count;

char line[256];

char *str[20];//to store the strings without commas

char ch[20];

int main (void) 

{

FILE *stream;

if ( (stream = fopen ( "test.txt", "r" )) == NULL )

{ printf ("Cannot read the new file\n");

exit (1);

}

while(fgets(line, sizeof line, stream))

{

printf ("%s", line); 

int length = strlen(line);

strcpy(ch,line);

for (i=0;i<length;i++)

{

 if (ch[i] != ',')
       {

 printf ("%c", ch[i]);   
        }

    }


}     

   //i++;




//FREE(x);
//FREE(y);
//FREE(z);

fclose (stream);

str[] 数组应该只存储像 a520 这样的值。(不包括逗号)

标签: c

解决方案


首先,除非绝对需要,否则不要使用全局变量。我假设您希望 str 作为指针数组,而 str[0] 存储第一行,str[1] 存储第二行,依此类推。为了这:

int line_pos = 0; //stores line_number
int char_pos = 0; //stores position in str[line_pos]
while(fgets(line, sizeof(line), stream))
    {
        printf ("%s", line); 
        int length = strlen(line);
        strcpy(ch,line);

        str[line_pos] = calloc(length, sizeof(char)); //allocating memory 

        for (i=0;i<length;i++)
        {
            if (ch[i] != ',')
            {

                *(str[line_pos]+char_pos) = ch[i]; //setting value of str[line][pos]
                char_pos++;
            }

        }
        char_pos = 0;
        line_pos++;
    }  
printf("%s", str[0]); //print first line without comma   

请注意,它仅适用于 20 行(因为您声明了 *str[20]),然后对于第 21 行或之后的行,它会导致溢出并可能导致各种灾难。您可以包括:

if (line_pos >= 20)
    break;

作为安全措施。

请注意,为 str 分配了稍微多一点的内存(分配的内存 = memory_required + 逗号数)。为了防止这种情况,您可以设置ch为不带逗号的文本:

for (i=0;i<length;i++)
        {
            int j = 0; //stores position in ch
            if (line[i] != ',')
            {

                ch[j++] = line[i]; 
            }

然后为 str[line_pos] 分配内存,例如: str[line_pos] = calloc(strlen(ch0, sizeof(char));


推荐阅读