0

Help with loop printing too many times [Solved but wondering if there's a more elegant solution]

The task is: /* Write a program that takes in a string representing a zip code. Output true or false if it is a valid zip code or not. A valid zip code is only numbers, must be 5 characters in length, and contain no spaces. Input Format: A string containing a zip code. Output Format: A string: true is the input is a valid zip code, or false, if it is not. Sample Input: 752f78 Sample Output: false */ Code works but "true" prints too many times : #include <cctype> #include <iostream> using namespace std; int main() { string str; cin >> str; int check; int strlen = str.length(); for (int i = 0; i < strlen; ++i) { check = isalpha(str[i]); if ((check > 0) || (str.length() > 5)){ cout << "false"; break; } else cout << "true"; } } return 0; } Any suggestions? Should I be using a different type of loop like while or do... while? Boolean? https://code.sololearn.com/c843d1ksTwqx/?ref=app

11th Nov 2022, 8:34 PM
Scott D
Scott D - avatar
2 Respostas
+ 2
The logic is not whole okay. This can be solved with a variable, which can be set depending of character test. After the for loop can be evaluated.
11th Nov 2022, 9:00 PM
JaScript
JaScript - avatar
0
JaScript Odd, I did not get a notification you had replied, I just saw it while updating the discussion title [Solved etc.]. Nonetheless I did find a solution (the above code now says "working", it passed all tests) . But I still wonder if there is a better/cleaner solution. All advice welcome since it would not just be giving me the solution (as I found one possible answer) but would help me improve☺ I realize hints are more valuable than just being given the solution!
12th Nov 2022, 12:34 AM
Scott D
Scott D - avatar