I am kinda new to C programming. I Need help to push a string from a file(test.txt) into an array without the commas

时间:2019-04-17 01:16:07

标签: c

I am trying to solve a problem on Dynamic memory allocation by reading the input from a file by malloc(),free(),realloc(); i just need help to push the strings into an array from the file, without the commas . My test.txt file are as follows:

a,5,0

a,25,1

a,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);

the str[] array should only store values like a520. (excluding the commas)

1 个答案:

答案 0 :(得分:0)

First of all DO NOT use global variables unless it is absolutely requires. I am assuming you want str as array of pointers and str[0] stores first line, str[1] stores second line and so on. For this:

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   

Note that it only works for 20 lines (because you declared *str[20]) and then for 21st or later lines it leads to overflow and can cause variety of disasters. You can include:

if (line_pos >= 20)
    break;

as a safety measure.

Note that slighty more memory is allocated for str(memory allocated = memory_required + number of comma). To prevent this you can set ch to text without comma:

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

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

Then allocate memory for str[line_pos] like: str[line_pos] = calloc(strlen(ch0, sizeof(char));