Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a full name by sscanf

Tags:

c++

c

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 ] ?

like image 361
masoud Avatar asked Mar 06 '13 19:03

masoud


People also ask

Can sscanf read from a file?

Reading a Text File Each line read from the file can be processed using the command sscanf (string scanf). sscanf is the same as scanf except it works on a string, rather than the input stream.

Why is sscanf unsafe?

The reason why sscanf might be considered bad is because it doesnt require you to specify maximum string width for string arguments, which could result in overflows if the input read from the source string is longer.

What does sscanf mean in C?

The sscanf() Function in C The sscanf() function allows us to read formatted data from a string rather than standard input or keyboard. Its syntax is as follows: Syntax: int sscanf(const char *str, const char * control_string [ arg_1, arg_2, ... ]);


1 Answers

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);
like image 142
jxh Avatar answered Nov 14 '22 22:11

jxh