How can I change the values of the system clock using C++? - c++

I've been trying to figure out how to use the system clock for a class project. The goal is to display the system's current time, then through inputs of 1-4 add one hour, minute, or second, then display the clock again. I think I have the basic framework down but I cannot figure out how to display the system time correctly as well as change the time itself. I have researched a few of the libraries to use and it gets pretty confusing with the pointers and the way it also always prints the date as well. I'm still new to C++ so my code is not the best especially when formatting the functions for the displays. Any help is appreciated.
When I run the program I want to print the local time from the PC it is running on, then receive input from the user (keystroke 1 - 4), then print the new time again. I don't want to actually change the time on my PC. For example say the current local time of my computer is 08:22:14, which will print to the screen. I wait any amount of time before I input selection 2. The new time will print 08:23:14.
#define _CRT_SECURE_NO_WARNINGS
#include <time.h> /* time_t, struct tm, time, localtime */
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw
#include <stdlib.h> // system(CLS);
#include <Windows.h>
#include <ctime>
using namespace std;
int DisplayClocks(int time) { // Function to write both clocks to screen
std::cout << std::setfill('*') << std::setw(26) << " " << std::setfill('*') << std::setw(26) << " " << endl; // First line of "*"
std::cout << "*" << std::setfill(' ') << std::setw(16) << "12 Hour Clock" << std::setfill(' ') << std::setw(4) << " *" << " "
<< "*" << std::setfill(' ') << std::setw(18) << "24 Hour Clock" << std::setfill(' ') << std::setw(6) << " *" << endl;
// 12 hour clock
std::cout << "*" << std::setfill(' ') << std::setw(6) << " " << time << std::setfill(' ') << std::setw(6) << " *" << " "
// 24 hour clock
<< "*" << std::setfill(' ') << std::setw(8) << " " << std::setfill(' ') << std::setw(8) << " *" << endl;
std::cout << std::setfill('*') << std::setw(26) << " " << std::setfill('*') << std::setw(26) << " " << endl; // Last line of "*"
return 0;
}
void DisplaySelection() { // Function to display selection menu for user
std::cout << std::setfill('*') << std::setw(26) << " " << endl;
std::cout << "*" << std::setfill(' ') << std::setw(19) << "1 - Add One Hour" << std::setfill(' ') << std::setw(5) << " *" << endl;
std::cout << "*" << std::setfill(' ') << std::setw(20) << "2 - Add One Minute" << std::setfill(' ') << std::setw(4) << " *" << endl;
std::cout << "*" << std::setfill(' ') << std::setw(20) << "3 - Add One Second" << std::setfill(' ') << std::setw(4) << " *" << endl;
std::cout << "*" << std::setfill(' ') << std::setw(19) << "4 - Exit Program" << std::setfill(' ') << std::setw(5) << " *" << endl;
std::cout << std::setfill('*') << std::setw(26) << " " << endl;
}
void main()
{
time_t now = time(0);
system("CLS");
string userVal;
DisplayClocks(now); // Call displayClocks on program start
DisplaySelection(); // Call DisplaySelection after display clocks
cin >> userVal; // Take user input to modify clock display
while (!( userVal == "Exit")) {
// FIX ME: Add functionality to clear screen every second
// FIX ME: Add displayClock to relevant if statements
if (userVal == "1") {
// Add One Hour to Clocks
// FIX ME: Functionality for Displaying 12 and 24 hour clocks
system("CLS"); // Clear screen test... working...
DisplayClocks(now); // Call displayClocks on program start
DisplaySelection(); // Call DisplaySelection after display clocks
cout << "1" << endl;
cin >> userVal;
}
else if (userVal == "2") {
// Add One Minute to Clocks
// FIX ME: Functionality for Displaying 12 and 24 hour clocks
system("CLS"); // Clear screen test... working...
DisplayClocks(now); // Call displayClocks on program start
DisplaySelection(); // Call DisplaySelection after display clocks
cout << "2" << endl;
cin >> userVal;
}
else if (userVal == "3") {
// Add One Second to Clocks
// FIX ME: Functionality for Displaying 12 and 24 hour clocks
system("CLS"); // Clear screen test... working...
DisplayClocks(now); // Call displayClocks on program start
DisplaySelection(); // Call DisplaySelection after display clocks
cout << "3" << endl;
cin >> userVal;
}
else if (userVal == "4") {
// Exit Program
// FIX ME: Functionality for Displaying 12 and 24 hour clocks
cout << "Program Ended" << endl;
break;
}
else{
// Prompt user to input correct selection when not userVal ! (1-4)
system("CLS"); // Clear screen test... working...
DisplayClocks(now);
DisplaySelection();
cout << "Error: Enter a selection 1 - 4." << endl;
cin >> userVal;
}
}
}

When you ask "How can I change SYSTEM <anything> in C++?", the keyword is "system".
It means that it's platform-dependent, so it needs a SYSTEM call - and I'm not speaking about the system function, but a call to your operating system's API, Win32 in your case. And a lot of these functions will requires elevation to work, on both Windows and Linux...
Unfortunately for you, changing system date and time is such a function, on both OS, and it isn't allowed to call it with a standard account.
Also, it has nothing related with C++, in fact. On Windows, you'll need to call SetSystemTime, and it's not a C++ feature but a function of kernel32.dll imported through sysinfoapi.h header (found in Windows SDK).
You'll get exactly the same answer in near any programming language: "Do a system call to SetSystemTime".

Related

How would I print a multi-line (non-standard) unicode string of text in C++? Updated for Clarity! (hopefully)

Rewriting this question with a bit more knowledge on what I'm requesting; (Thank you James Risner and Turtle for your assistance, but I didn't word this correctly and got different responses than what was needed)
I am currently in the process of writing a program for my class in which I print out non-standard Unicode characters in a string. These characters are direct copies from a website, and not in u\ #### standard copy, but rather the unicode characters pre-selected. The program I am running this on is Clion, building my program using mingw's ninja build settings.
My issue that I'm experiencing is that my output, rather than the unicode characters, is instead a random array of (I think) unrelated characters. Printing this in Clion's Debug menu outputs the proper output, but printing it in the runtime or in its own external file all output the issue.
Below is an exact copy of my code (character for character) DO NOT REUSE PLEASE :(
#include <iostream>
#include <string>
#include <windows.h>
#define _WIN32_WINNT 0x0500
#include <thread>
#include <chrono>
#include <random>
using namespace std;
static int Range(int start, int end){
random_device rd;
mt19937 rng(rd());
uniform_int_distribution<int> dist(start,end);
return dist(rng);
}
int main() {
system("color 0F");
HWND consoleWindow = GetConsoleWindow();
int windowSize = 390;
MoveWindow(consoleWindow, windowSize,windowSize,windowSize,windowSize, TRUE); // This program and the one below it not only locks the window size, but also locks the window at a fixed display pixel length/width
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
ShowScrollBar(GetConsoleWindow(), SB_VERT, 0);
string name = "\033[91m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n\033[92m███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗\n\033[93m████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║\n\033[94m██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║\n\033[95m██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║\n\033[96m██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║\n\033[91m╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝\n\033[92m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
float balance = Range(1,50000);
float withD, cSelect;
int x = 0;
while (name[x] != '\0') {
cout << name[x] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
x++;
}
Sleep(2);
std::cout << '\n' << endl;
string bottomBar = "\033[93m░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░\n";
string systName = "\033[94mModeni Systems LLC";
cout << " ";
cout << systName << "\n";
std::cout << '\n' << endl;
int y = 0;
while (bottomBar[y] != '\0') {
cout << name[y] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
y++;
}
string Input;
cout << "\n \033[92mPlease Input your Name...\n\n ";
getline(cin, Input);
cout << endl;
cout << " Welcome " << Input << "!" << endl;
cout << " Please select a number from the options below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.) View your Balance\n 2.) Make a withdrawal\n 3.) Deposit\n 4.) Customer Support\n 5.) Log Out Securely\n" << endl;
cout << bottomBar << endl;
cin >> cSelect;
while(cSelect != 5){
if(cSelect==1){
cout << "Your current balance is... " << balance << " dollars!\n \n" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==2){
cout << "Please enter the amount you'd like to withdraw!\n" << endl;
cin >> withD;
if(withD>balance){
cout << "Sorry, you do not have that much money! Please try again... " << endl;
} else if(withD<=balance) {
balance = balance - withD;
cout << "Successfully taken out " << withD << " dollars!\n" << "Your new balance is " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
}
} else if(cSelect==3){
cout << "Please enter the amount you'd like to deposit!" << endl;
double depAm;
cin >> depAm;
balance = balance + depAm;
cout << "Your new balance is now " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << "1.)View your Balance\n2.)Make a withdrawal\n3.)Deposit\n4.)Customer Support\n5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==4){
cout << bottomBar << "\n" << endl;
cout << "Hello! This is Modeni's Self-Service Assistant!\n Please describe your problem below! \n" << endl;
string proB;
cin >> proB;
int chatF;
chatF = Range(0,5);
if(chatF==0){
cout << "We're so sorry to hear that! Please wait as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==1){
cout << "Sorry to hear that you're currently having that problem! Please sit tight as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==2){
cout << "That's not good! Please wait just a moment as we get you in touch with someone who can help.\n" << endl;
} else {
cout << "Ouch! Just give us a moment while we put you in touch with someone who can help!\n" << endl;
}
Sleep(10000);
string nameSt;
int nameVar;
nameVar = Range(0,5);
if(nameVar == 1)
nameSt = "Raphael";
else if(nameVar == 2)
nameSt = "Marie";
else if(nameVar == 3)
nameSt = "Joesph";
else
nameSt = "Marian";
cout << " \033[94m░█░█ " << nameSt << " has joined the chat █░█░" << endl;
Sleep(Range(3000,8000));
cout <<"\n >> Just a moment while I look over your concern.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Alright. I'm sorry you're dealing with this problem right now. Let's put you in touch with one of our call-in agents to assist you further.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Their number is - 1-(918)-335-1300.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Is there anything else I can help you with today? \n" << endl;
return 0;
}
}
return 0;
}
I am specifically writing this program for windows, and I have yet to find a solid fix without re-writing the entirety of my code.
The intended output is photograph 1, and the actual output is photograph 2. Any and all help is appreciated!
Photograph 1
Photograph 2
There is no problem with your program. There is a problem with your display.
% cc -o modeni modeni.cpp -lc++
% ./modeni
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗
████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║
██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║
██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║
██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║
╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
% echo $TERM
xterm-256color
I am using a macOS system and this works with TERM=xterm-256color on both iTerm2 and Terminal.
What is TERM?
This environment variable advises applications what terminal emulation is required to display characters on screen properly. An application will use the termcap/terminfo database to look up the proper escape sequences to display colors, move or manipulative text on screen, and other effects.
I only ever see xterm-256color now. Why?
Modern terminal applications assume the output will be in xterm-256color format. Many no longer have an option to choose another format.
AFAIK there is no standard way in C++ to process unicode in standard io, and different OSs' default consoles will behave differently if you just make the unicode string as std::string to output; E.g. in Windows cmd maybe you need _setmode(_fileno(stdout), _O_U16TEXT); to show UTF-16 strings correctly.
Good news is that in C++23 there will be <print> to (hopefully, not definitely so far) help solve this troublesome problem.

setw() not working properly on my code

I'm having problem with my code not sure if it's a bug or there is something wrong with my code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setfill('*') << setw(80) << "*";
cout << setw(21) << "Mt.Pleasant Official Billing Statement" << endl;
cout << setfill('*') << setw(80) << "*" << endl;
return 0;
}
Adding manual spaces works but I want to add spaces programmatically but when I tested the application this what it looks like :
setw does not move the text but sets the minimum width it should take
To achieve what you have in mind you should experiment with a bigger value since your string is longer than 21 characters, e.g.
cout << setfill('*') << setw(80) << "*" << endl;
cout << setfill(' ') << setw(56) << "Mt.Pleasant Official Billing Statement" << endl;
cout << setfill('*') << setw(80) << "*" << endl;
Output:
********************************************************************************
Mt.Pleasant Official Billing Statement
********************************************************************************

setw not working as expected

I'm trying to print time in hh:mm format but when the time is like 01:01 it prints as 1:1. Here's my code:
void output(int hour, int min, char ampm){
cout << setw(2) << setfill('0') << "The time is: " << hour << ":" << min << " ";
if(ampm == 'P'){
cout << "PM";
}
else if (ampm == 'A'){
cout << "AM";
}
}
As I understand it, this should work. I include iomanip. Can you see anything wrong with it?
The width is a special formatting setting: While all other formatting flags are stick, the width() will be reset by each output operator (well, you can have user-defined output operators which don't reset the width() but doing so would not follow the normal style). That is, you need to set the width immediately prior to the output that should be affected:
std::cout << std::setfill('0')
<< std::setw(2) << hour << ':'
<< std::setw(2) << min << ' ';
Following is correct way:
cout<<""The time is: ";
cout << setfill('0') <<setw(2) << hour << ":" <<setw(2) << min << " ";
Ref :-this

C++ setw moving whole line not just the needed part

I am trying to use setw to clean up the output of my program. I want the empty spaces in between "total number of spools to be ordered" and the output.
EDIT this is what im going for:
and this is what I get
here is what I have so far:
UPDATED CODE
/********************************************/
// Name: results /
// Description: Print results /
// Parameters: N/A /
// Reture Value: N/A /
/********************************************/
void results(int spoolnumber, int subtotalspool, float shippingcost, float totalcost)
{
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << spoolnumber << endl << endl;
cout << left << setw (45) << "The subtotal for the spools is:" << right << "$" << subtotalspool << endl << endl;
cout << "The shipping cost is: $" << shippingcost << endl << endl;
cout << "The total cost is: $" << totalcost << endl << endl;
return;
}
You can also do
cout << left << setw (45) << "Total number of spools to be ordered is: " << spoolnumber << endl << endl;
to choose which side the padding goes. The default is left.
EDIT: using stringstream
stringstream ss;
ss << "$" << spoolnumber
I think you can fix the right end by adding another setw. So:
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << setw(5) << ss.str() << endl << endl;

C++ - How to reset the output stream manipulator flags [duplicate]

This question already has answers here:
Restore the state of std::cout after manipulating it
(9 answers)
Closed 4 years ago.
I've got a line of code that sets the fill value to a '-' character in my output, but need to reset the setfill flag to its default whitespace character. How do I do that?
cout << setw(14) << " CHARGE/ROOM" << endl;
cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl;
I thought this might work:
cout.unsetf(ios::manipulatorname) // Howerver I dont see a manipulator called setfill
Am I on the wrong track?
Have a look at the Boost.IO_State_Savers, providing RAII-style scope guards for the flags of an iostream.
Example:
#include <boost/io/ios_state.hpp>
{
boost::io::ios_all_saver guard(cout); // Saves current flags and format
cout << setw(14) << " CHARGE/ROOM" << endl;
cout << setfill('-') << setw(11) << '-' << " " << setw(15) << '-' << " " << setw(11) << '-' << endl;
// dtor of guard here restores flags and formats
}
More specialized guards (for only fill, or width, or precision, etc... are also in the library. See the docs for details.
You can use copyfmt to save cout's initial formatting. Once finished with formatted output you can use it again to restore the default settings (including fill character).
{
// save default formatting
ios init(NULL);
init.copyfmt(cout);
// change formatting...
cout << setfill('-') << setw(11) << '-' << " ";
cout << setw(15) << '-' << " ";
cout << setw(11) << '-' << endl;
// restore default formatting
cout.copyfmt(init);
}
You can use the ios::fill() function to set and restore the fill character instead.
http://www.cplusplus.com/reference/iostream/ios/fill/
#include <iostream>
using namespace std;
int main () {
char prev;
cout.width (10);
cout << 40 << endl;
prev = cout.fill ('x');
cout.width (10);
cout << 40 << endl;
cout.fill(prev);
return 0;
}
You can manually change the setfill flag to whatever you need it to be:
float number = 4.5;
cout << setfill('-');
cout << setw(11) << number << endl; // --------4.5
cout << setfill(' ');
cout << setw(11) << number << endl; // 4.5
The null character will reset it back to the original state:
setfill('\0')