PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to test if a user inputted string is valid in do/while loop?

 July 30, 2022     c++, do-while, loops, validation     No comments   

Issue

So essentially, I am asking the user for a departure time, as well as if it is in the AM or PM. In the code provided, I only test for AM/am (caps or lowercase), but in my actual program I will be testing for both AM/am and PM/pm. Now, when I set my do/while loop up like this:

do {
    cout << "Please Enter a Valid Period: ";
    cin >> departure_amOrPM;
} while (departure_amOrPM != "AM");

it works just fine, and it lets the program continue when "AM" is entered in all caps. But when I add another test to my loop like this:

do {
    cout << "Please Enter a Valid Period: ";
    cin >> departure_amOrPM;
} while (departure_amOrPM != "AM" || departure_amOrPM != "am");

it does not work. I tried entering both "AM" and "am", yet it did not let me continue. I don't know how to overcome this obstacle, so any help or tips would be much appreciated. Thanks!


Solution

Think about this condition

} while (departure_amOrPM != "AM" || departure_amOrPM != "am");

This condition is true of every string. Every string is either not equal to "AM" or not equal to "am" (most strings are not equal to both). That's why you couldn't proceed.

What you meant to write is this

} while (departure_amOrPM != "AM" && departure_amOrPM != "am");

It's very common to get && and || confused, especially when also dealing with negation.



Answered By - john
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing