Judge the end of string parsing with sscanf

Source: Internet
Author: User

When sscanf is used to parse strings, it is easy to handle errors: sscanf returns the number of domains actually parsed and assigned values to determine if they are consistent with the expected values.

Today, we encountered a resolution address bug because the address book "127.0.0.1: 30000" was written as "127.0.0.1: 30000: 127.0.0.1: 30000". It was originally parsed using sscanf, if the result is equal to 5, it is considered correct, but no additional characters are determined.

 

Fixed:

Bool assign (const char * SRC)
{
Unsigned int B1, B2, B3, B4;
Char dummy; // catch extra Character

Int COUNT = sscanf (SRC, "% u. % u % C
", & B1, & B2, & B3, & B4, & dumm
Y );
If (COUNT = 4 & B1 <256 & b2 <256 & B3 <256 & B4 <256)
{
Assign (unsigned char) B1, (unsigned char) B2, (unsigned char) B3, (unsigned char) B4 );
Return true;
}
Return false;
}

Then read an extra character. If it matches, it is an error.

 

Another method is to use % N:

Bool assign (const char * SRC)
{
Unsigned int B1, B2, B3, B4;
Int bytes_parsed ;//

Int COUNT = sscanf (SRC, "% u. % u % N
", & B1, & B2, & B3, & B4 ,&
Bytes_parsed
);
If (COUNT = 4 & bytes_parsed =
Strlen (SRC)
& B1 <256 & b2 <256 & B3 <256 & B4 <256)
{
Assign (unsigned char) B1, (unsigned char) B2, (unsigned char) B3, (unsigned char) B4 );
Return true;
}
Return false;
}

% N puts the number of bytes read into the int type result.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.