Thread: adding specific chars from file to an array

  1. #1
    Registered User
    Join Date
    Dec 2013
    Posts
    10

    adding specific chars from file to an array

    lets say we have a txt that contains this


    | | | | |*| |
    | | | |*| | |

    and that symbolizes a 2x6 char array and we want to take only the symbols inside the || and place them in a 2x6 char array.
    how do we do that?

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    You could process each line by reading it into a buffer e.g. with fscanf. Then use sscanf to pull out each element from your string, e.g.

    Code:
    char example[] = "| | | | |*| |";    
    char buf[6][2] = {"", "", "", "", "", ""};
    sscanf(example, "|%1[ *]|%1[ *]|%1[ *]|%1[ *]|%1[ *]|%1[ *]|", 
        buf[0], 
        buf[1], 
        buf[2], 
        buf[3], 
        buf[4], 
        buf[5]);
    for (int i = 0; i < 6; i++) {
        printf("%d: %s\n", i, buf[i]);
    }
    This assumes that you have at exactly one character in between each | symbol, however. To avoid this requirement, you could process the line using strtok or scan it character by character for the needed information.
    Last edited by c99tutorial; 01-29-2014 at 07:53 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array of structs(adding/deleting elements to a file)
    By boebae in forum C Programming
    Replies: 8
    Last Post: 09-22-2013, 02:10 PM
  2. Replies: 13
    Last Post: 11-27-2011, 04:45 PM
  3. help with read/write file/array of chars
    By JustJonny in forum C Programming
    Replies: 8
    Last Post: 02-08-2011, 02:24 PM
  4. Reading chars from file into array
    By AJOHNZ in forum C++ Programming
    Replies: 1
    Last Post: 08-19-2009, 03:37 PM
  5. read specific number of chars from stream
    By ch4 in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2008, 12:49 PM