C++/Even when I include cstdlib.
Expert: vijayan - 12/9/2008
QuestionOkay I did have include <cstdlib> and it still won't run and gives the "expected constructor destructor" error.
I also have tried without using cstdlib and done your way and it wouldn't still run.
Here's your way:
#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" ;
}
}
And here's my way:
#include <ctype.h>
#include <iostream>
#include <string>
#include <cstdlib>
int main()
{
std::string gender ;
// accept string from user
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() == 1 )
{
// 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 )
{
cout << "ERROR! gender is incorrect\n" ;
}
}
system("pause");
return 0;
I'm trying to run it my way using <cstdlib> as you have said because std:: I haven't learnt C but instead learn the basics of c++. What's wrong this time? ;(
Answer> Here's your way:
#include <ctype.h>
// ...
int main()
{
// ...
}
this compiles fine without warnings or errors.
$g++43 -Wall -std=c++98 -pedantic -Werror yourway.cc
$
And here's my way:
#include <ctype.h>
// ...
int main()
{
// ...
}
system("pause");
return 0;
this does give errors. and it should.
$g++43 -Wall -std=c++98 -pedantic -Werror myway.cc
myway.cc:37: error: expected constructor, destructor, or type conversion before '(' token
myway.cc:38: error: expected unqualified-id before 'return'
$
there is a very good reason for these errors.
system("pause");
return 0;
are in the global scope (outside main). these are simply not allowed there.