An example of creating a stream-enabled object
#include
#include
#include
#include
#include
using namespace std;
std::string timestamp();
class logstatement;
ostream& operator<<(ostream&
ost, const logstatement& ls);
class logstatement
{
public:
logstatement(std::string
s): data(s), time_string( timestamp() )
{
};
friend
ostream& operator<<(ostream&, const logstatement&);
private:
std::string
data;
std::string
time_string;
};
ostream&
operator<<(ostream& ost, const logstatement& ls)
{
ost<<"~|"<
return
ost;
}
std::string timestamp()
{
ostringstream
stream;
time_t
rawtime;
tm
* timeinfo;
time(&rawtime);
timeinfo
= localtime( &rawtime );
stream
<< (timeinfo->tm_year)+1900<<"
"<tm_mon
<<"
"<tm_mday<<"
"<tm_hour
<<"
"<tm_min<<"
"<tm_sec;
return
stream.str();
}
int main(int argc, char** argv)
{
if(argc<2 span="">2>
{
return
-1;
}
ostringstream
log_data;
for(int
i=1;i
{
log_data<
}
logstatement
log_entry(log_data.str());
clog<
ofstream
logfile("logfile",ios::app);
if
( ! logfile )
{
return
-1;
}
logfile<
logfile.close();
return
0;
}
Pointers or references for polymorphism
#include
#include
#include
using namespace std;
class stringconvertable
{
public:
virtual string toString () =
0;
};
void displayobject (stringconvertable*
obj)
{
cout
<< obj->toString() << '\n';
}
The C++ Modulus Operator
#include
#include
using namespace std;
int main()
{
int num;
cin >> num;
if ( num % 2 == 0 )
{
cout << num << " is
even ";
}
return 0;
}
Getting Random Values in C and C++ with Rand
#include
#include
#include
using namespace std;
int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
cout<< rand() << endl;
cout<< rand() << endl;
cout<< rand() << endl;
return 0;
}
C++
Code program
#include
#include
#include
#include
const int low = 1;
const int high = 6;
using namespace std;
int main()
int first_die, sec_die;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
first_die = rand() % (high - low + 1) + low;
sec_die = rand() % (high - low + 1) + low;
cout<< "Your roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
first_die = rand() % (high - low + 1) + low;
sec_die = rand() % (high - low + 1) + low;
cout<< "My roll is (" << first_die << ", "
<< sec_die << "}" << endl << endl;
return 0;
}
No comments:
Post a Comment