5 years, 11 months ago.

How to "parse" a document

Hello community. I have a "local" document with many lines. I want to spend each line sequentially on the display. But the problem is that I need to split each line. I think it's called "parsing". Can you tell me how to "parse" a line that looks like this: (Each line looks the same. I just want to output the parts of a line and then the next line override)

0.123456 1 99 xx d 8 01 02 03 04 05 06 07 08 Length

And I need it 4 small parts and build the output on the screen:

# 1:. 0.123456
# 2:. 99
# 3:. 8
# 4:. 01 02 03 04 05 06 07 08

Since I am beginner, please take some consideration;-) I have absolutely no idea how I can reacting.

My code should now look like this:

#include "mbed.h"
#include "stdio.h"
#include "SPI_TFT_ILI9341.h"
#include "string"
#include "Arial12x12.h"
#include "Arial24x23.h"
#include "Arial28x28.h"
#include "font_big.h"

SPI_TFT_ILI9341 TFT(p5, p6, p7, p8, p9, p10,"TFT");     
LocalFileSystem local("local");                        

int main ()

    TFT.set_font((unsigned char*) Neu42x35);         
    printf("My Test ");

    FILE *fp = fopen("/local/test.asc","r");          
    if(!fp) {
        TFT.set_font((unsigned char*) Arial28x28);
        printf("File not Found");                      

    TFT.set_font((unsigned char*) Arial12x12);
    printf("#1: %s", a);
    printf("#2: %s", b);
    printf("#3: %s", c);
    printf("#4: %s", d);

Is every line the same number of bytes? Do the data you want appear at the same position in every line?

posted by Stephen Paulger 13 Oct 2014

1 Answer

5 years, 11 months ago.

The safest and easiest way is to read each line in a string with fgets (reads upto newline) and then parse that string with sscanf(string, format string, variable pointers...) Carefully read the sscanf documentation for the different format specifiers, how to skip fields etc. Also test the return value of sscanf because it tells you how many fields were converted. Please note that the %s specifier will stop at whitespace. you can use %c with a width specifier but you have to know the width in advance. In your example you could use the format string "%s%*s%s%*s%*s%s%23c" which will read the float as a string (a), skip the second field (1), read the 99 as a string (b), skip two fields, read the 8 as a string (c) and read 23 characters as an array of characters (d). You will need to append the '\0' yourself.

Accepted Answer