Advertisement
janac

Validate string input from from console

Nov 5th, 2021 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // Receive input from the user. If it starts with a vowel,
  6. // store the word. If not, ask to re-enter the input.
  7.  
  8. // This function takes a character and returns
  9. // true if it is a vowel. Otherwise, it returns false.
  10. int is_vowel(char letter)
  11. {
  12.     // The character must be one of these.
  13.     string vowels = "AaEeIiOoUu";
  14.  
  15.     // Go from the beginning to the
  16.     // end of the list of vowels.
  17.     for (size_t i = 0; i < vowels.size(); ++i)
  18.     {
  19.         // If the letter matches that vowel.
  20.         if (letter == vowels[i])
  21.         {
  22.             // The letter is a vowel.
  23.             return true;
  24.         }
  25.     }
  26.  
  27.     // The letter didn't match any vowel.
  28.     return false;
  29. }
  30.  
  31. int main()
  32. {
  33.     string input; // User input.
  34.  
  35.     cout << "Enter a word that starts with a vowel:" << endl;
  36.     getline(cin, input); // Get the user's input.
  37.  
  38.     char first_letter = input[0]; // Get the first letter.
  39.     bool valid = is_vowel(first_letter); // Test the first letter.
  40.  
  41.     while (!valid) // While the letter is not a vowel,
  42.     {
  43.         cout << "Your word doesn't start with a vowel.\n";
  44.         cout << "Please enter a word that starts with a vowel:" << endl;
  45.         getline(cin, input); // Get new input.
  46.         first_letter = input[0]; // Get the first letter.
  47.         valid = is_vowel(first_letter); // Test the first letter.
  48.     }
  49.  
  50.     cout << "Thank you!";
  51.  
  52.     return 0;
  53. }
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement