// eMailAddress.cpp
// Tests whether a string entered by the user
// represents a valid E-mail address.

#include <iostream>
#include <string>

int main()
{
   cout << "Enter a string:>";
   string text;
   cin >> text;

   // Prepare to examine characters is string:
   bool validAddress = true;      // innocent until proven guilty
   char previous = '\0';          // No actual previous character yet
   bool atFound = false;          // We haven't yet seen the '@'.
   bool dotFoundAfterAt = false;  // No dot yet found to right of '@'.

   // Examine first and last character:
   if ( text[0] == '@' || text[text.length()-1] == '@'
                       || text[text.length()-1] == '.' )
   {
      validAddress = false;
   }  // if

   // Examine entire string one character at a time:
   for ( int i = 0; i < text.length() && validAddress; i++ )
   {
      if ( text[i] == '@' )
      {
         if ( atFound    // i.e. if there was a previous '@'
              || previous == '.' )
         {
            validAddress = false;
         }  // if
         atFound = true;
      }  // if '@'
      else if ( text[i] == '.' )
      {
         if ( previous == '.' || previous == '@' )
            validAddress = false;
         if ( atFound )
            dotFoundAfterAt = true;
      }  // if '.'
      else if ( ! (    ( text[i] >= 'a' && text[i] <= 'z' )
                    || ( text[i] >= 'A' && text[i] <= 'Z' )
                    || ( text[i] >= '0' && text[i] <= '9' )
                    || text[i] == '-'
                    || text[i] == '_' ) )
      {
         validAddress = false;
      } // if not any of the other allowed characters

      // Keep track of current character
      // when examining next character:
      previous = text[i];
   }  // for i

   if ( !dotFoundAfterAt )
      validAddress = false;

   if ( validAddress )
      cout << "\"" << text
           << "\" is a valid E-mail address." << endl;
   else
      cout << "\"" << text
           << "\" is NOT a valid E-mail address." << endl;

   return 0;
}  // function main