In code C, How can I erase special characters from a char array?

Discussion in 'C' started by 3nc31, Nov 16, 2007.

  1. 3nc31

    3nc31 New Member

    Joined:
    Nov 16, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I have this code:
    Code:
    int readConfig(char *IP, int *p, char Myfile[]){
    char dir[32];
    char pto[32];
    char c='a';
    FILE *fp;
    int i=0;
    
    if((fp=fopen(Myfile,"r"))==NULL){
    return -1;
    }
    while(c!=EOF && c!='\n'){
    c=getc(fp);
    if(c!=EOF && c!='\n'){
    dir[i++]=c;
    
    }
    }
    
    i=0;
    c='a';
    
    while(c!=EOF && c!='\n'){
    c=getc(fp);
    if(c!=EOF && c!='\n'){
    pto[i++]=c;
    }
    }
    
    *puerto=atoi(pto);
    strcpy(IP, dir);
    return 0;
    }
    and the file contains this information: 255.255.255.255
    5555

    Well, when I print the IP value, this is the result
    IP: 255.255.255.255fhv���

    How can I do for fix it??? I want that only print: IP: 255.255.255.255

    Thanks!!!!
     
    Last edited by a moderator: Nov 16, 2007
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,335
    Likes Received:
    377
    Trophy Points:
    83
    Because your 5555 is converted into ASCII as that character.
     
  3. Salem

    Salem New Member

    Joined:
    Nov 15, 2007
    Messages:
    133
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Please don't PM me for 1:1 support.
    > Well, when I print the IP value, this is the result
    > IP: 255.255.255.255fhv���
    You don't append a \0 to the string you build up, so you get a random amount of trailing junk until the print function just happens to find a \0.

    Also, your c variable should be an int if you want to compare it with EOF properly.
    Consider this loop a simplification (and safer).
    Code:
    int c;
    while ( i < 31 && (c=getc(fp)) != EOF && c != '\n' ) {
      dir[i++]=c;
    }
    dir[i] = '\0';
    
    But this very near to what fgets() does for you anyway, so perhaps consider using that to read a line rather than inventing it yourself one character at a time.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice