Home > database >  Is there a way combine a specific number of chars from fgetc?
Is there a way combine a specific number of chars from fgetc?

Time:01-19

I have found some information about strcat and experimented with it but it doesn't work the way i expected for example :

char a = 'a', b = 'b';
strcat(a,b);
printf("%c", a);

this will produce an error "initialization of 'char' from 'char *' makes integer from pointer without a cast". Is there a way to unite chars until the wanted word is complete and store it in 1 variable? Or am i going completely wrong about this. The purpose of the code is to read an xml file and build a tree with the tags. Any help is or advice is very much appreciated.

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

int main() {
    int count = 0;
    char c, word;
    FILE *file = fopen("example.xml", "r");
    if (file == NULL) {
        return 0;
    }

    do {
        c = fgetc(file);

        if (c == '<') {
            count = 1;
        }
        if (c == '>') {
            count = 0;
            printf(">");
        }
        if (count == 1) {
            printf("%c", c);
            
        }
        if (feof(file)){
            break ;
        }   
    } while(1);

    fclose(file);
    return(0);
}

CodePudding user response:

I'm not sure exactly what you're trying to accomplish, but you could try something like the following, which will print every <tag>, i.e., every string in the file between <...>'s , and will also accumulate them in an array of strings called tags[]. And note that you'd might want to add checks that avoid going over the 99 chars/tag and 999 tags total. But if this isn't anything like what you're actually trying to do, maybe clarify the question.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    int ntags=0, nchars=0;
    char c, tags[999][99];
    FILE *file = fopen("example.xml","r");
    if (file==NULL) return(0);
    while(1) {
        c = (char)fgetc(file);
        if (nchars==0 && c!='<') continue;
        tags[ntags][nchars  ] = c
        if (c=='>') {
          tags[ntags][nchars] = '\000';
          printf("tag#%d = %s\n",ntags 1,tags[ntags]);
          nchars=0; ntags  ; }
        if (feof(file)) break ;
        }
     /* do you now want to do anything with your tags[] ??? */ 
     fclose(file);
     return(0);
     }

CodePudding user response:

You are trying to use a function, those parameters are char *

char *strcat(char *dest, const char *src)

but you gave strcat a char but it wants a char*

int main()
{
    char str1[20] = "this";
    char str2[] = "is";

     strcat(str1, str2);

     printf("%s", str1);

return 0;

}

this is the way i thinkt you want it

  •  Tags:  
  • Related