简体   繁体   中英

Read a full name by sscanf

I'm using C++, but I decided to parse the lines of a log file with sscanf . After reading each line, it should extract data and store them to variables.

string test = "[06/03/2013 18:15:23] INFO - Open [Johny Cage]";

int day, month, year, second, minute, hour;
char name[128];

int c = sscanf(test.c_str(), "[%d/%d/%d %d:%d:%d] INFO - Open [%127[^\n]%c]",
               &day, &month, &year, &second, &minute, &hour, name);

if (c == 7)
{
    cout << name << endl;
}

I need read the name as Johny Cage (The name maybe has spaces) and store it to name , but the output is:

Johny Cage]

The problem is the trailing ] . How can I use sscanf which it doesn't read last ] ?

Use [^]] instead of [^\\n] . Also, remove the %c at then end of your scan format string.

int c = sscanf(test.c_str(), "[%d/%d/%d %d:%d:%d] INFO - Open [%127[^]]]",
               &day, &month, &year, &second, &minute, &year, name);

By checking against it. Try this:

int c = sscanf(test.c_str(), "[%d/%d/%d %d:%d:%d] INFO - Open [%127[^\]\n]]%*[^\n]\n",
           &day, &month, &year, &second, &minute, &year, name);

] has to be escaped, otherwise it would be understood as 'end of delimiter string', which would then be empty...and thereby illegal.

With this addition, it will stop at a linebreak or a ], whatever occurs first.

And of course remove that %c...after all, you don't save it to any variable.

The last addition will read to the next newline character it finds and discard any signs it finds along the way (thus the *).

Im not sure whats going with the way you match the name, but this works for me:

int c = sscanf(test.c_str(), "[%d/%d/%d %d:%d:%d] INFO - Open [%[^]]"

This matches anything except the end bracket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM