Can you explain me what's happening in my code? | Sololearn: Learn to code for FREE!

0

Can you explain me what's happening in my code?

Im asking this because I successfully did the Zip Code Validator challenge but I don't know what coded so it works. Here is my code: https://code.sololearn.com/cS0RMsKjv7ed/?ref=app

8/14/2022 6:28:07 PM

eloufou

7 Answers

New Answer

+1

Your program 1) contains undefined behaviour and 2) does not actually fulfill the specification, as far as I understand it. For example, you report true for inputs like "1 2 3", "1234a", and "abcde", which are five characters long, but contain invalid characters. I'm honestly a bit perplexed that none of the test cases cover such a case. 1) Local variables are not default-initialized to any value, so `numberCharacters` could contain any value when you start incrementing it. You should set it to zero explicitly. Also, myString[i] as a condition is technically undefined behaviour, since you access the string out of bounds (technically because methods as c_str() basically force a null character to be stored after the actual data). A safer approach would be a range-based for loop: for (char c : myString) ... 2) The if-condition can never be true, as a character cannot be equal to multiple different values at the same time. That means you practically just count the number of characters in the string.

0

Shadow Well... if I understand, I'm just lucky that my code worked edit: I think those challenge are not my level

0

Yes, kind of, since the test cases seem to be poorly designed. You can basically pass all of them by simply verifying the input is five characters long, completely forgoing the check for letters and spaces. Here is a sample fix that should work, although it could be solved more efficiently: https://code.sololearn.com/cSYiCkBfNWQV/?ref=app

0

Shadow So basically, your code first check if there is letter or other character than number and breaks the for loop if there is not only number. After it looks if the zip code is 5 character long.

0

Correct.

0

Shadow Is the for loop useless since the if statement look for the length of the zip code with the 'myString.size'? edit: like the for loop only check for the letter but dosent output 'false' if it not only number

0

Please help,I need to give input to test case 1 and case 2 to be read at once in my project     Question: You are making a program for a bus service. A bus can transport 50 passengers at once. Given the number of passengers waiting in the bus station as input, you need to calculate and output how many empty seats the last bus will have. https://code.sololearn.com/c3ESvvgB7uqh/?ref=app