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 ]
?
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.
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.
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, ... ]);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With