From the course: Secure Coding in C++

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Solution: Secure a data parsing function

Solution: Secure a data parsing function - C++ Tutorial

From the course: Secure Coding in C++

Solution: Secure a data parsing function

(light music) - [Instructor] Here's my solution. We start by adding two validation functions, isValidKey and isValidValue. isValidKey checks that the key isn't empty and only contains alphanumeric characters or underscores. isValidValue checks that the value isn't empty and contains only digits. Then inside parseSettings, we improve the logic. In line 35, before extracting the key and value, we check if the equal sign is present and not at the beginning or end of the string. Then in lines 41 and 42, we validate the key and value using our helper functions and skip any pair that fails the check. In line 43, we also skip duplicates by checking if the key already exists in the map. Let's run it with a messy input to test all five edge cases, plus a few valid ones. All right, here it goes, =10,key=,with space=5,foo=bar,valid1=100, valid2=200, then valid1 again equals 999, not valid. And lastly, valid3=300. As expected, it ignores the invalid ones, missing equal sign, empty, empty value…

Contents