Reputation: 93
I recently picked up a c++ book, " A Complete Guide to Programming in C++," and I can't seem to get an example to compile properly. I imagine it's a version issue, but I can't seem to find anything about this version of the 'time' function ever even working.
Has the 'time' function usage changed recently?
#include <iostream>
#include <string>
#include <iomanip>
#include <cctype>
#include <ctime>
using namespace std;
long timediff(void);
static string secret = "ISUS";
static long maxcount = 3, maxtime = 60;
bool getPassword()
{
bool ok_flag = false;
string word;
int count = 0, time = 0;
timediff();
while (ok_flag != true && ++count <= maxcount)
{
cout << "\n\nInput the password: ";
cin.sync();
cin >> setw(20) >> word;
time += timediff();
if (time >= maxtime)
break;
if (word != secret)
cout << "Invalid password!" << endl;
else
ok_flag = true;
}
return ok_flag;
}
long timediff()
{
static long sec = 0;
long oldsec = sec;
time( &sec);
return (sec - oldsec);
}
Yields the following error when I build...
1>d:\c++ training\learning\learning\source.cpp(39): error C2664: 'time_t time(time_t *const )': cannot convert argument 1 from 'long *' to 'time_t *const '
1>d:\c++ training\learning\learning\source.cpp(39): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "Learning.vcxproj" -- FAILED.
Upvotes: 1
Views: 81
Reputation: 170064
The signature of std::time
is
std::time_t time( std::time_t* arg );
Where std::time_t
is defined as:
typedef /* unspecified */ time_t;
The book assumes long
is the unspecified type. That is a poor lesson to any programmer. And you are learning it the hard way, because the typedef changes, but the code sample does not.
The whole point of a type alias like this is to abstract implementation details away. And allow you to write portable code. The assumption that the book makes about the alias is unfounded. And is a sign that the author should not be teaching anyone C++.
Upvotes: 7