Digital clock c++ - c++

Making a digital clock in c++ and I get these errors:
expected ; before reloj
statement is a reference, not call, to funcion 'time'
statement has no effect
''reloj'' is undeclared (first use this function)
Each undeclared identifier is reported only once for each function it appears
#include<iostream>
#include<Windows.h>
using namespace std;
struct time
{
int hr,mint,seg;
};
int main()
{
time reloj;
reloj.hr = 0;
reloj.mint = 0;
reloj.seg = 0;
for(int i = 0; i<24; i++)
{
if(reloj.hr == 23)
{
reloj.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(reloj.mint == 59)
{
reloj.mint = 0;
}
for(int k = 0; k<60; k++)
{
if(reloj.seg == 59)
{
reloj.seg = 0;
}
cout<<reloj.hr<<" : "<<reloj.mint<<" : "<<reloj.seg<<endl;
reloj.seg++;
Sleep(1000);
system("Cls");
}
reloj.mint++;
}
reloj.hr++;
}
}

using namespace std; in the global namespace is a bad idea, and is probably dumping std::time there, along with a host of other names. This will clash with your time class.
Unfortunately, simply removing the evil using isn't a solution here, since time comes from the C library. Implementations are allowed to (and many do) dump names from the C library into the global namespace whether you want them there or not.
So your options are:
Rename your class, or put it in your own namespace;
Refer to it as struct time rather than just time;
Don't include any standard library headers, just in case they mess with your global names.

I have Another codes :
#include <iostream>
#include <unistd.h>
#include <ctime>
using namespace std;
void Timer()
{
int HOUR = 0, MINUTE = 0 , SECOND = 0;
time_t now = time(0);
tm *ltm = localtime(&now);
HOUR = ltm->tm_hour;
MINUTE = ltm->tm_min;
SECOND = ltm->tm_sec;
while(true)
{
system("clear");
cout << HOUR << ":" << MINUTE << ":" << SECOND << endl;
SECOND ++;
if(SECOND == 60)
{
MINUTE++;
SECOND = 0;
if(MINUTE == 60);
{
HOUR++;
MINUTE = 0;
if(HOUR ==24)
{
HOUR = 0;
}
}
}
sleep(1);
}
}
int main()
{
Timer();
}
*IF YOU USE THIS ON WINDOWS THEN CHANGE system("clear") into system("cls")

Related

C++ async and deferred show no difference in time compared to only async

I am creating a C++ program that uses 100 random number generators. The number generators are split into two groups: ones that create 100 numbers and ones that create 10 000 000 numbers.
I am trying to see the difference between:
Using deferred launching for the 100 numbers and async for the 10 000 000 numbers.
Using only async for both types of number generators.
There's no difference in time, so my code has something wrong with it, but so far I haven't been able to find it because I am a beginner with C++.
Below is the code. I've commented the part that uses only async.
#include <iostream>
#include <chrono>
#include <future>
#include <list>
/*
Using both deferred and async launchings: 5119 ms
Using only async launching: 5139 ms
*/
using namespace std;
class RandomNumberGenerator
{
public:
enum class task { LIGHT, HEAVY };
task taskType;
RandomNumberGenerator(): taskType(task::LIGHT)
{
int rnd = rand() % 2;
if (rnd == 0)
{
taskType = task::LIGHT;
}
else
{
taskType = task::HEAVY;
}
}
bool generateNumbers()
{
int number;
if(taskType == task::LIGHT)
{
for (int i = 0; i < 100; i++)
{
number = rand();
}
}
else
{
for (int i = 0; i < 1000000; i++)
{
number = rand();
}
}
return true;
}
};
int main()
{
cout << "Starting to generate numbers\n";
RandomNumberGenerator objects[100];
auto start = chrono::system_clock::now();
for (int i = 0; i < 100; i++)
{
objects[i].generateNumbers();
future<bool> gotNumbers;
if (objects[i].taskType == RandomNumberGenerator::task::LIGHT)
{
gotNumbers = async(launch::deferred, &RandomNumberGenerator::generateNumbers, &objects[i]);
}
else
{
gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]);
}
bool result = gotNumbers.get();
//future<bool> gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]);
//bool result = gotNumbers.get();
}
auto end = chrono::system_clock::now();
cout << "Total time = " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " seconds\n";
}
using launch::deferred or launch::async the same amount of work still needs to be done the only difference is whether it is done on another thread and the current thread blocks waiting for that thread to finish when you call gotNumbers.get() or whether the result is calculated directly in the current thread when you call gotNumbers.get(). Either way you aren't gaining any performance by using additional threads as only one thread is ever executing at a time.
If you start executing the async work before calling objects[i].generateNumbers() you might see more difference (though the overhead of std::async might still outweigh the performance increase).
#if 1
future<bool> gotNumbers;
if ( objects[ i ].taskType == RandomNumberGenerator::task::LIGHT )
{
gotNumbers = async( launch::deferred, &RandomNumberGenerator::generateNumbers, &objects[ i ] );
}
else
{
gotNumbers = async( launch::async, &RandomNumberGenerator::generateNumbers, &objects[ i ] );
}
#else
future<bool> gotNumbers = async(launch::async, &RandomNumberGenerator::generateNumbers, &objects[i]);
#endif
objects[ i ].generateNumbers();
bool result = gotNumbers.get();

Why do I keep getting unresolved externals for my program?

I keep getting unresolved externals when I try to run this code in Visual Studio.
Structure Time Assignment for College
Create a structure called Time that has members days, hours, minutes,
and seconds as ints.
Create an instance of Time and initialize the members.
Create a function to normalize the time when values are added to it.
For example, after adding values to the hours, call the normalize
function which should see if the hours > 24.
If so, add 1 to the days member and reset hours by subtracting 24
from the current value.
DO the same for minutes and seconds over 59.
Your main program should add values to hours, minutes and seconds and
after each, call the normalize function to properly set the values.
Output the members after each update. Assume hours use a 24-hour
clock.
#include <iostream>
using namespace std;
Struct time
{
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
};
void normalize();
int main()
{
int clockRepeating;
for (clockRepeating = 0; clockRepeating < 150; clockRepeating++)
{
normalize();
}
return 0;
}
void normalize(Time &timenormalize)
{
if (timenormalize.days > 31)
timenormalize.days = 1;
if (timenormalizehours > 24)
{
timenormalize.hours = 0;
timenormalize.days++;
}
if (timenormalize.minutes > 59)
{
timenormalize.minutes = 0;
timenormalize.hours++;
}
if (time normalize.seconds > 59)
{
timenormalize.seconds = 0;
timenormalize.minutes++;
cout << timenormalize.days, timenormalize.hours, timenormalize.minutes, timenormalize.seconds;
}
else
timenormalize.seconds++;
cout << timenormalize.days, timenormalize.hours, timenormalize.minutes,timenormalize.seconds;
The signature you declared for void normalize(); does not match the signature as it's defined in this file (void normalize(Time &timenormalize)).
Here's a fixed up version of your code. First the compilation errors:
changed Struct to struct: struct is a key word, must be lowercase;
changed Time to struct time in void normalize(..): symbols are case sensitive: Time isn't declared, but struct time is;
added missing . to if (timenormalizehours): if (timenormalize.hours);
added } to the end of the file (probably copy/paste error).
And then the linker error undefined reference to 'normalize':
change function declaration void normalize() to void normalize(struct time &): you declare the normalize function without parameters, but define it with one parameter.
And then finally the compilation error this introduces:
change the normalize(); call to normalize( mytime ); because it takes a paramter
and declare a local variable struct mytime to pass as the parameter.
#include <iostream>
using namespace std;
struct time
{
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
};
void normalize(struct time &);
int main()
{
int clockRepeating;
struct time mytime;
for (clockRepeating = 0; clockRepeating < 150; clockRepeating++)
{
normalize( mytime );
}
return 0;
}
void normalize(struct time &timenormalize)
{
if (timenormalize.days > 31)
timenormalize.days = 1;
if (timenormalize.hours > 24)
{
timenormalize.hours = 0;
timenormalize.days++;
}
if (timenormalize.minutes > 59)
{
timenormalize.minutes = 0;
timenormalize.hours++;
}
if (timenormalize.seconds > 59)
{
timenormalize.seconds = 0;
timenormalize.minutes++;
cout << timenormalize.days, timenormalize.hours, timenormalize.minutes, timenormalize.seconds;
}
else
timenormalize.seconds++;
cout << timenormalize.days, timenormalize.hours, timenormalize.minutes,timenormalize.seconds;
}
It prints a series of 0. Now it's up to you to put some values in struct time mytime. I hope this helps!

Directly setting values of struct tm's attributes not working

Why does asctime(ptr) return nothing? All the variables of the struct have values. Can someone explain why does this happen?
I also tried using strftime but the result was the same.
#include <iostream>
#include <ctime>
#include <new>
//#include <cstdio>
using namespace std;
int main(int argc,char *argv[])
{
struct tm *ptr=new struct tm;
//char buf[50];
ptr->tm_hour=0;
ptr->tm_mon=0;
ptr->tm_year=0;
ptr->tm_mday=0;
ptr->tm_sec=0;
ptr->tm_yday=0;
ptr->tm_isdst=0;
ptr->tm_min=0;
ptr->tm_wday=0;
cout << asctime(ptr);
//strftime(buf,sizeof(char)*50,"%D",ptr);
//printf("%s",buf);
return 0;
}
The below program works. Remove zero with 1 and it will work.
struct tm *ptr = new struct tm();
char buf[50];
ptr->tm_hour = 1;
ptr->tm_mon = 1;
ptr->tm_year = 1;
ptr->tm_mday = 1;
ptr->tm_sec = 1;
ptr->tm_yday = 1;
ptr->tm_isdst = 1;
ptr->tm_min = 1;
ptr->tm_wday = 1;
cout << asctime(ptr)
This also works:
ptr->tm_hour = 0;
ptr->tm_mon = 0;
ptr->tm_year = 0;
ptr->tm_mday = 1;
ptr->tm_sec = 0;
ptr->tm_yday = 0;
ptr->tm_isdst = 0;
ptr->tm_min = 0;
ptr->tm_wday = 0;
cout << asctime(ptr);
The behavior of asctime is undefined if any member of struct tm is outside its normal range.
Especially the behavior is undefined if the calendar day is less than 0 (some implementations handle tm_mday==0 as meaning the last day of the preceding month).
Take a look at http://en.cppreference.com/w/cpp/chrono/c/asctime and http://en.cppreference.com/w/cpp/chrono/c/tm for further details.

Call to function is ambiguous in C++. Candidate functions are the Prototype and the function itself

I am working through Stanford CS106B C++ assignments and I have a 'semantic issue' with an assignment.
It seems as if the compiler cannot deduce whether the call is to a function or to the prototype of the function. I don't understand why a call would ever be made to the prototype. How can I make it so that the call is made to the function rather than the prototype? The error message I get it "Call to 'humansTurn' is ambiguous".
The error messages relate to the calls of the humansTurn(Lexicon,Lexicon) function, within the humansTurn(Lexicon,Lexicon) function, at the bottom of the page. The prototype for this function is above the main function.
Any help would be greatly appreciated.
Kind regards,
Mehul
/*
* File: Boggle.cpp
* ----------------
*/
#include <iostream>
#include "gboggle.h"
#include "graphics.h"
#include "grid.h"
#include "vector.h"
#include "lexicon.h"
#include "random.h"
#include "simpio.h"
using namespace std;
/* Constants */
const int BOGGLE_WINDOW_WIDTH = 650;
const int BOGGLE_WINDOW_HEIGHT = 350;
const string STANDARD_CUBES[16] = {
"AAEEGN", "ABBJOO", "ACHOPS", "AFFKPS",
"AOOTTW", "CIMOTU", "DEILRX", "DELRVY",
"DISTTY", "EEGHNW", "EEINSU", "EHRTVW",
"EIOSST", "ELRTTY", "HIMNQU", "HLNNRZ"
};
const string BIG_BOGGLE_CUBES[25] = {
"AAAFRS", "AAEEEE", "AAFIRS", "ADENNN", "AEEEEM",
"AEEGMU", "AEGMNN", "AFIRSY", "BJKQXZ", "CCNSTW",
"CEIILT", "CEILPT", "CEIPST", "DDLNOR", "DDHNOT",
"DHHLOR", "DHLNOR", "EIIITT", "EMOTTT", "ENSSSU",
"FIPRSY", "GORRVW", "HIPRRY", "NOOTUW", "OOOTTU"
};
/* Function prototypes */
void welcome();
void giveInstructions();
// Create random board
static Grid <char> randomBoard();
// Create custom board
static Grid<char> customBoard();
static void drawAndFillBoard(Grid<char>);
static void humansTurn(Lexicon,Lexicon);
int main() {
initGraphics(BOGGLE_WINDOW_WIDTH, BOGGLE_WINDOW_HEIGHT);
welcome();
giveInstructions();
string custom = getLine("Type y to create custom board:" );
Grid<char> gridData;
if (custom=="y"){
gridData = customBoard();
} else {
gridData = randomBoard();
}
drawAndFillBoard(gridData);
Lexicon english("EnglishWords.dat");
// Lexicon holds words previously encountered
Lexicon previousWords;
humansTurn(english, previousWords);
return 0;
}
/*
* Function: welcome
* Usage: welcome();
* -----------------
* Print out a cheery welcome message.
*/
void welcome() {
cout << "Welcome! You're about to play an intense game " << endl;
}
/*
* Function: giveInstructions
* Usage: giveInstructions();
* --------------------------
* Print out the instructions for the user.
*/
void giveInstructions() {
cout << endl;
cout << "The boggle board is a grid onto which I ";
cout << "or triple your paltry score." << endl << endl;
cout << "Hit return when you're ready...";
getLine();
}
static Grid<char> randomBoard(){
Vector<string> standardCubes;
for(int i = 0; i<16;i++){
standardCubes.add(STANDARD_CUBES[i]);
}
// Shuffle cubes
for (int i = 0; i < standardCubes.size(); i++) {
int r = randomInteger(i, standardCubes.size()-1);
if (i!=r){
string stringToMove1 = standardCubes.get(i);
string stringToMove2 = standardCubes.get(r);
standardCubes.set(r, stringToMove1);
standardCubes.set(i, stringToMove2);
}
}
// Update grid with random side of cube
Grid<char> gridData(4, 4);
int counter = 0;
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
string s = standardCubes.get(counter);
int r = randomInteger(0, 5);
gridData[columnNo][rowNo] = s[r];
counter++;
}
}
return gridData;
}
static Grid<char> customBoard(){
Grid<char> gridData(4,4);
string s = getLine("Please enter 16 characters to make up the custom board. Characters will fill the board left to right, top to bottom: ");
for (int i = 0; i < s.length(); i++) {
s[i] = toupper(s[i]);
}
if (s.length()<16){
cout << "String has to be 16 characters long, try again" << endl;
customBoard();
}
int i =0;
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
gridData[columnNo][rowNo] = s[i];
i++;
}
}
return gridData;
}
static void drawAndFillBoard(Grid<char> gridData){
drawBoard(4, 4);
for (int columnNo = 0; columnNo <4; columnNo++){
for (int rowNo = 0; rowNo<4; rowNo++) {
labelCube(rowNo, columnNo, gridData[rowNo][columnNo]);
}
}
}
static void humansTurn(Lexicon englishWords, Lexicon &previousWords){
/*
Human’s turn (except for finding words on the board). Write the loop that allows the user to enter words. Reject words that have already been entered or that don’t meet the minimum word length or that aren’t in the lexicon. Use the gboggle functions to add words to the graphical display and keep score.
*/
string humanGuess = getLine("Please enter your guess: ");
for (int i = 0; i < humanGuess.length(); i++) {
humanGuess[i] = tolower(humanGuess[i]);
}
if (humanGuess.length()<4){
cout << "Min guess length is four characters" << endl;
humansTurn(englishWords, previousWords);
}
if (!englishWords.contains(humanGuess)) {
cout << "That word is not English, please try another word" << endl;
humansTurn(englishWords, previousWords);
}
if (previousWords.contains(humanGuess)){
cout << "That word has already been guessed, please try another word" << endl;
humansTurn(englishWords, previousWords);
}
// check if word can be made using data on board
}
Your function humansTurn definition has different signature with declaration
function declaration:
static void humansTurn(Lexicon,Lexicon);
Function definition:
static void humansTurn(Lexicon englishWords, Lexicon &previousWords)
^^
//Here

I'm having some scope issue (unidentified identifier error after a for loop)

I'm using visual studio 2008 to do some problems and brusg up on using c++. I have an error and I don't know why it occurs. Here's all the code. The error occurs on the line :
cout<<levels[0][0]->left->value;
with error:
error C2065: 'levels' : undeclared identifier
a shorthand of what's happening to levels is this:
//declaring it
binaryValNode*** levels;
levels = new binaryValNode** [size];
//adding arrays to the array:
for(int i = 0;i<size;i++){
levels[i] = new binaryValNode* [size];
//adding the objects
for(int k = 0; k <= i ; k++)
{
levels[i][k] = new binaryValNode();
}
//I tested cout here and it works fine
}
//but loses scope here(?)
binaryValNode is a struct with int value,binaryValNode* left and binaryValNode* right.
thanks!
code:
#include <iostream>
#include <fstream>
#include "binaryValNode.h"
using namespace std;
int main() {
int length = 0;
int size = 0;
ifstream myReadFile;
myReadFile.open("input.txt");
char* c = new char[3];
if (myReadFile.is_open()) {
while (myReadFile.getline(c,(size+1)*3)) {
size++;
c = new char[(size+1)*3];
}
binaryValNode*** levels;
levels = new binaryValNode** [size];
myReadFile.clear();
myReadFile.seekg(0);
for(int i = 0;i<size;i++){
levels[i] = new binaryValNode* [size];
c = new char[(i+1)*3];
myReadFile.getline(c,(i+1)*3);
for(int k = 0; k <= i ; k++)
{
levels[i][k] = new binaryValNode();
if(c[3*k] != '0')
{
levels[i][k]->value = ((int) c[(3*k)+1]-48) + 10*((int) c[(3*k)]-48);
}
else
{
levels[i][k]->value = (int) c[(3*k)+1]-48;
}
//
if(i!=0){
if(k==0){//only left parent
levels[i-1][k]->left = levels[i][k];
}
else if(k==i){//only right parent
levels[i-1][k-1]->right = levels[i][k];
}
else{
levels[i-1][k]->left = levels[i][k];
levels[i-1][k-1]->right = levels[i][k];
}
}
}
}
}
myReadFile.close();
cout<<levels[0][0]->left->value;
cin.get();
return 0;
}
Fix your indentation (for example, gg=G in Vim).
Right now you have
int main() {
// ...
if (myReadFile.is_open()) {
// ...
binaryValNode*** levels;
// ...
}
// ...
cout << levels[0][0]->left->value;
// ...
}
where levels is very clearly out of scope.
This needs to be moved to before the conditional:
binaryValNode*** levels;
Sort out your indentation - it will show that you have one too may closing }, and hence the problem line occurs after the end of main().
Try edit/advanced/format-selection