You are here:

C++/here's the code

Advertisement


Question
okay here it is. i just want it to get over with.

#include <cstdlib>
#include <iostream>
#include <string>

string gender;

bool ok = true ;
if( gender.empty() ) ok = false ;
else if( ( gender.size() 1 ) && ( gender[0] != 'm' ) && ( gender[0] != 'f' ) ) ok = false ;
else if( ( gender != "male" ) && ( gender != "female" ) ) ok = false ;
if( !ok )
{
 cout << "ERROR! gender is incorrect\n" ;
}

for( size_t i=0 ; i < gender.size() ; ++i )
  gender[i] = tolower( gender[i] ) ;

Answer
ok. here are the errors in the code.

   1. the gender string has to be accepted from the user. add std::cin >> gender ;

   2. the string has to be converted to all lower case *before* (not after) the checks are made.

   3. in the first place, your code would not compile at all:
         a. the function (main) is missing
         b. you need to either have a using directive or qualify names in the std namespace with std::
         c. gender.size() 1 is an error, it should be gender.size() == 1

here is the corrected code (annotated with comments):

#include <ctype.h>
#include <iostream>
#include <string>

int main()
{
   std::string gender ;

   // accept string from user
   std::cin >> gender ;

   // first convert all chars to lower case
   for( size_t i=0 ; i < gender.size() ; ++i )
       gender[i] = ::tolower( gender[i] ) ;

   bool ok = true ;

   // an empty string is not ok
   if( gender.empty() ) ok = false ;

   else if( gender.size() == 1U )
   {
       // a single char was entered, must be either 'f' or 'm'
       if( ( gender[0] != 'm' ) && ( gender[0] != 'f' ) ) ok = false ;
   }

   // more than one char entered, must be either "male" or "female"
   else if( ( gender != "male" ) && ( gender != "female" ) ) ok = false ;

   if( !ok )
   {
       std::cout << "ERROR! gender is incorrect\n" ;
   }
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.