Trying to get some data from CallNtPowerInformation(SystemPowerInfomation…) but the returned data doesn't seem to be correct (lidpresent should be true but it's false, VideoDimPresent should be false but it's true..) I'm new to C++ and I'm pretty sure I'm doing something wrong.
My code:
#include <NTstatus.h>
#define WIN32_NO_STATUS
#include <windows.h>
#include <Powrprof.h>
#include <iostream>
#pragma comment(lib, "Powrprof.lib")
int main()
{
SYSTEM_POWER_CAPABILITIES spwr;
NTSTATUS status = ::CallNtPowerInformation(SystemPowerInformation, NULL, 0, &spwr, sizeof(SYSTEM_POWER_CAPABILITIES));
if(STATUS_SUCCESS == status){
if(spwr.LidPresent){
std::cout << "LidPresent TRUE!" << std::endl;
}else{
std::cout << "LidPresent FALSE!" << std::endl;
}
if(spwr.VideoDimPresent){
std::cout << "VideoDimPresent TRUE!" << std::endl;
}else{
std::cout << "VideoDimPresent FALSE!" << std::endl;
}
if(spwr.SystemS1){
std::cout << "SystemS1 TRUE!" << std::endl;
}else{
std::cout << "SystemS1 FALSE!" << std::endl;
}
if(spwr.SystemS2){
std::cout << "SystemS2 TRUE!" << std::endl;
}else{
std::cout << "SystemS2 FALSE!" << std::endl;
}
if(spwr.SystemS3){
std::cout << "SystemS3 TRUE!" << std::endl;
}else{
std::cout << "SystemS3 FALSE!" << std::endl;
}
if(spwr.SystemS4){
std::cout << "SystemS4 TRUE!" << std::endl;
}else{
std::cout << "SystemS4 FALSE!" << std::endl;
}
}
else
{
std::cout << "CallNtPowerInformation failed. Status: " << status << std::endl;
}
return status;
}
You passed SystemPowerInformation, so lpOutputBuffer is expected to point to SYSTEM_POWER_INFORMATION structure.
You may want to pass SystemPowerCapabilities rather than SystemPowerInformation if you expect SYSTEM_POWER_CAPABILITIES.
See CallNtPowerInformation documentation.
Related
Forgive me if this is an obvious fix as I am very much a novice when it comes to C++.
For my assignment, we were given some starter code that simulates a command-line crypto trading platform. Originally, you would be prompted to type in commands 1 to 6 to do things like print exchange stats, make an offer, print the wallet and such. For my assignment, I've been asked to create an advisor bot that takes in string commands such as 'help' and processes this to return the appropriate output.
Naturally, since there was already a system in place to do this with integers as inputs, I tried to tweak the functions (I didn't do a lot yet) so they take string commands instead and output accordingly.
Before anything else, I would like to know why the function getUserOption and input is underlined red in the while loop of the init function, but in the actual function there are no errors:
This is the contents of the header file
#pragma once
#include <vector>
#include "OrderBookEntry.h"
#include "OrderBook.h"
#include "Wallet.h"
#include <string>
using namespace std;
class MerkelMain
{
public:
MerkelMain();
/** Call this to start the sim */
void init();
private:
void advisorBot();
void printHelp();
void printMarketStats();
void enterAsk();
void enterBid();
void printWallet();
void gotoNextTimeframe();
std::string getUserOption();
void processUserOption(string userOption);
void printCurrentTime();
std::string currentTime;
// OrderBook orderBook{"20200317.csv"};
OrderBook orderBook{"20200601.csv"};
Wallet wallet;
};
This is the cpp file
#include "MerkelMain.h"
#include <iostream>
#include <vector>
#include "OrderBookEntry.h"
#include "CSVReader.h"
#include <string>
using namespace std;
MerkelMain::MerkelMain()
{
}
void MerkelMain::init()
{
int input;
currentTime = orderBook.getEarliestTime();
wallet.insertCurrency("BTC", 10);
while(true)
{
advisorBot();
input = getUserOption();
processUserOption(input);
}
}
void MerkelMain::advisorBot()
{
std::cout << "Please enter a command, or help for a list of commands" << std::endl;
std::cout << "============== " << std::endl;
std::cout << "Current time is: " << currentTime << std::endl;
}
/*void MerkelMain::printMenu()
{
// 1 print help
std::cout << "1: Print help " << std::endl;
// 2 print exchange stats
std::cout << "2: Print exchange stats" << std::endl;
// 3 make an offer
std::cout << "3: Make an offer " << std::endl;
// 4 make a bid
std::cout << "4: Make a bid " << std::endl;
// 5 print wallet
std::cout << "5: Print wallet " << std::endl;
// 6 continue
std::cout << "6: Continue " << std::endl;
std::cout << "============== " << std::endl;
std::cout << "Current time is: " << currentTime << std::endl;
}*/
void MerkelMain::printHelp()
{
std::cout << " The available commands are help, help cmd, prod, min, max, avg, predict, time, step " << std::endl;
}
void MerkelMain::printMarketStats()
{
for (std::string const& p : orderBook.getKnownProducts())
{
std::cout << "Product: " << p << std::endl;
std::vector<OrderBookEntry> entries = orderBook.getOrders(OrderBookType::ask,
p, currentTime);
std::cout << "Asks seen: " << entries.size() << std::endl;
std::cout << "Max ask: " << OrderBook::getHighPrice(entries) << std::endl;
std::cout << "Min ask: " << OrderBook::getLowPrice(entries) << std::endl;
}
}
void MerkelMain::enterAsk()
{
std::cout << "Make an ask - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterAsk Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::ask
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterAsk Bad input " << std::endl;
}
}
}
void MerkelMain::enterBid()
{
std::cout << "Make an bid - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::bid
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterBid Bad input " << std::endl;
}
}
}
void MerkelMain::printWallet()
{
std::cout << wallet.toString() << std::endl;
}
void MerkelMain::gotoNextTimeframe()
{
std::cout << "Going to next time frame. " << std::endl;
for (std::string p : orderBook.getKnownProducts())
{
std::cout << "matching " << p << std::endl;
std::vector<OrderBookEntry> sales = orderBook.matchAsksToBids(p, currentTime);
std::cout << "Sales: " << sales.size() << std::endl;
for (OrderBookEntry& sale : sales)
{
std::cout << "Sale price: " << sale.price << " amount " << sale.amount << std::endl;
if (sale.username == "simuser")
{
// update the wallet
wallet.processSale(sale);
}
}
}
currentTime = orderBook.getNextTime(currentTime);
}
std::string MerkelMain::getUserOption()
{
std::string userOption = "";
std::string line;
//std::cout << "Type in 1-6" << std::endl;
std::getline(std::cin, line);
try{
userOption = std::stoi(line);
}catch(const std::exception& e)
{
//
}
std::cout << "You chose: " << userOption << std::endl;
return userOption;
}
void printCurrentTime()
{
std::cout << "Current time is: " << currentTime << std::endl;
}
void MerkelMain::processUserOption(string userOption)
{
if (userOption == "help")
{
printHelp();
}
if (userOption == "help cmd")
{
printMarketStats();
}
if (userOption == "prod")
{
enterAsk();
}
if (userOption == "min")
{
enterBid();
}
if (userOption == "max")
{
printWallet();
}
if (userOption == "avg")
{
gotoNextTimeframe();
}
if (userOption == "predict")
{
enterAsk();
}
if (userOption == "time")
{
enterBid();
}
if (userOption == "step")
{
gotoNextTimeframe();
}
}
Your getUserOption() function returns a std::string. This means when you wrote:
input = getUserOption();
In the above statement the right hand side is of type std::string. On the other hand, the left hand side is of type int. So there is mismatch in the type of left hand side and right hand side expressions. Hence the error.
You can solve this by changing the type of variable input to std::string. So replace int input; by:
std::string input; //type changed to std::string
I am learning about different stream state flags/functions in C++ such as good(), goodbit, bad(), badbit and so on. While testing with std::cin, I am unable to pass cin as an argument to a function (the compiler shows a lot of errors)
#include <iostream>
#include <sstream>
void print_state (const std::istream& stream) {
std::cout << " good()=" << stream.good();
std::cout << " eof()=" << stream.eof();
std::cout << " fail()=" << stream.fail();
std::cout << " bad()=" << stream.bad();
}
int main() {
std::cin.clear (std::ios::goodbit);
std::cout << "goodbit: " << print_state(std::cin) << std::endl;
std::cin.clear (std::ios::eofbit);
std::cout << "eofbit: " << print_state(std::cin) << std::endl;
std::cin.clear (std::ios::failbit);
std::cout << "failbit: " << print_state(std::cin) << std::endl;
std::cin.clear (std::ios::badbit);
std::cout << "badbit: " << print_state(std::cin) << std::endl;
return 0;
}
Desired output:
goodbit: good()=1 eof()=0 fail()=0 bad()=0
eofbit: good()=0 eof()=1 fail()=0 bad()=0
failbit: good()=0 eof()=0 fail()=1 bad()=0
badbit: good()=0 eof()=0 fail()=1 bad()=1
I know I can call the function directly with cin, such as std::cin.good(), but I want to know how can I pass cin as an argument to a function.
Edit:
I get a LOT of errors during compilation. An example:
F:\cpp_programming\stream_states.cpp: In function 'int main()':
F:\cpp_programming\stream_states.cpp:13:27: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'void')
std::cout << "goodbit: " << print_state(std::cin) << std::endl;
~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
Since print_state does not return a value, it cannot be used with the insertion operator <<. The simplest way to correct this, is to call print_state on its own.
print_state(std::cin);
The corrected code is given below:
#include <iostream>
#include <sstream>
void print_state (const std::istream& stream) {
std::cout << " good()=" << stream.good();
std::cout << " eof()=" << stream.eof();
std::cout << " fail()=" << stream.fail();
std::cout << " bad()=" << stream.bad();
}
int main() {
std::cin.clear (std::ios::goodbit);
std::cout << "goodbit: "; print_state(std::cin); std::cout << std::endl;
std::cin.clear (std::ios::eofbit);
std::cout << "eofbit: "; print_state(std::cin); std::cout << std::endl;
std::cin.clear (std::ios::failbit);
std::cout << "failbit: "; print_state(std::cin); std::cout<< std::endl;
std::cin.clear (std::ios::badbit);
std::cout << "badbit: "; print_state(std::cin); std::cout << std::endl;
return 0;
}
To answer my own question
cin can be passed to a function as a function argument, such as:
functionName(std::cin);
Currently I am trying to learn SFML networking but I am having a problem with the client (I think).
#include <iostream>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
int main()
{
sf::TcpSocket sock;
sf::Packet backpack;
sf::Thread Thread;
std::cout <<"Attempting to connect to server" << std::endl;
sf::Socket::Status status = sock.connect("127.0.0.1", 25568);
if (status != sf::Socket::Done){
std::cout << "Could Not Connect to server" << std::endl;
} else {
std::cout << "Connected to server" << std::endl;
}
backpack << 9;
std::cout << "Sending data" << std::endl;
sock.send(backpack);
std::cout << "Sent the data" << std::endl;
std::cout << "Client task completed" << std::endl;
return 0;
}
Here is The server code
#include <iostream>
#include <SFML/Network.hpp>
int main()
{
std::cout << "Server Has started" << std::endl;
sf::TcpSocket peer;
sf::TcpListener ear;
sf::Packet backpack;
if (ear.listen(25568) != sf::Socket::Done){
std::cout << "Listerner failed to be setup, another program may be using that port." << std::endl;
} else {
std::cout << "Server is ready" << std::endl;
}
if (ear.accept(peer) != sf::Socket::Done){
std::cout << "Client refused connection" << std::endl;
} else {
std::cout << "Client connection Accepted" << std::endl;
}
peer.receive(backpack);
std::cout << "Data recieved" << std::endl;
int num;
backpack >> num;
std::cout << num << std::endl;
std::cout << "hello world" << std::endl;
return 0;
}
When running the server and client (In either order) The client will output nothing after the message "Attempting to connect to server" appears, And the server outputs nothing after the message "Server is ready" Please help =) I have been stuck on this problem for a while.
Not sure why SendMessage isn't getting the text from the class I need. I have done this before but it was is VisualBasic and I wanted to port it over to c++. I have not tried this code on any other program. I was reading something about it possibly being unicode but I wasn't sure on how to implement that.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
using namespace std;
void FindmIRC()
{
cout << "[mIRC]" << endl;
cout << "- find mIRC window" << endl;
HWND hwndmIRC = FindWindow(L"mIRC", NULL);
if (NULL != hwndmIRC)
{
cout << " + found mIRC window" << endl;
cout << "- find MDIClient window" << endl;
HWND hwndMDIClient = FindWindowEx(hwndmIRC, NULL, L"MDIClient", NULL);
if (NULL != hwndMDIClient)
{
cout << " + found MDIClient window" << endl;
cout << "- find mIRC_Channel window" << endl;
HWND hwndmIRC_Channel = FindWindowEx(hwndMDIClient, NULL, L"mIRC_Channel", NULL);
if (NULL != hwndmIRC_Channel)
{
cout << " + found mIRC_Channel window" << endl;
cout << "- find Static window" << endl;
HWND hwndStatic = FindWindowEx(hwndmIRC_Channel, NULL, L"Static", NULL);
if (NULL != hwndStatic)
{
cout << " + found Static window" << endl;
cout << "- get text length" << endl;
int textLen = (int)SendMessage(hwndStatic, WM_GETTEXTLENGTH, 0, 0);
if (0 < textLen)
{
cout << "- getting text" << endl;
const int bufferSize = 1024;
char textBuffer[bufferSize] = "";
SendMessage(hwndStatic, WM_GETTEXT, (WPARAM)bufferSize, (LPARAM)textBuffer);
cout << "[begin text]" << endl;
cout << textBuffer << endl;
cout << "[end text]" << endl;
}
else
{
cerr << "No text." << endl;
}
}
else
{
cerr << "Static not found." << endl;
}
}
else
{
cerr << "mIRC_Channel not found." << endl;
}
}
else
{
cerr << "MDIClient not found." << endl;
}
}
else
{
cerr << "mIRC not open." << endl;
}
}
int main()
{
FindmIRC();
return 0;
}
The highlighted class is what has the text:
The program find the class with no problem and does not report not finding it so I don't see a reason why it should not find it. Any help is great!
As you can see on your spy++ output, highlighted control does not contain any text. It should appear on the left of Static in "".
I'm trying to control the connect method timeout, but I didn't find the appropriate mean.
Just to be clear, I'm not talking about the Idle connection timeout(ConnectTimeoutOption).
The scenario I need to deal with is a database gone away, and my server has to cope with that. My current handling of things is that I'm pinging the server, and If I notice that the ping failed, I'm suspending the queries for 100 seconds. After that I'm trying to reestablish the connection. The problem is that if the database is still dead, than the connect method takes about 20 seconds to answer (can be simulated by just pulling the network cable), which is way too much for me.
This should work for you
#include <mysql++.h>
#include <cstdio>
int main()
{
mysqlpp::Connection conn;
conn.set_option(new mysqlpp::ReconnectOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(5));
const std::string db="mysql_cpp_data";
const std::string query_text="SELECT count(*) as total FROM stock";
conn.connect(db.c_str(), "somehost", "user", "pass");
try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
}
std::cout << "Make database go away now and press a key\n";
getchar();
try
{
mysqlpp::Query query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << std::endl;
std::cout << "Make database come back now and press a key\n";
getchar();
while(!conn.ping())
{
sleep(1);
std::cout << "Waiting for DB to come back\n";
}
if(!conn.select_db(db))
{
std::cout << "Failed to change DB\n";
}
}
try
{
mysqlpp::Query query=conn.query();
query=conn.query();
query << query_text;
mysqlpp::StoreQueryResult res=query.store();
std::cout << "Has " << (*res.begin())[0] << " rows\n";
}
catch(const mysqlpp::BadQuery &e)
{
std::cout << "EXCEPTION: " << e.what() << " " << e.errnum() << std::endl;
}
return 0;
}
try this out.
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmdline.h>
#include <mysql++.h>
#define DBS "library"
#define USR "root"
#define PAS "rootsman"
using namespace std;
using namespace mysqlpp;
int main(int argc, char *argv[]) {
//for true cgi but in this case it works, kind of baffling!
mysqlpp::examples::CommandLine cmdline(argc, argv, USR, PAS);
if (!cmdline) return 1;
mysqlpp::Connection conn(true);
conn.set_option(new mysqlpp::ReconnectOption(true));
conn.set_option(new mysqlpp::ConnectTimeoutOption(5));
conn.connect(DBS, cmdline.server(), cmdline.user(), cmdline.pass());
try {
mysqlpp::String sql("select firstname from person");
mysqlpp::Query query = conn.query(sql);
mysqlpp::StoreQueryResult res = query.store();
mysqlpp::StoreQueryResult::const_iterator it;
int count = 1;
for (it = res.begin(); it != res.end(); ++it) {
mysqlpp::Row row = *it;
cout << count << "\t" << row[0] << endl;
++count;
}
} catch (const mysqlpp::BadQuery& bq) {
cerr << "query error: " << bq.what() << endl;
return -1;
}
cout << "\nmake database fly away now by pressing a key>" << endl;
getchar();
try {
mysqlpp::Query query = conn.query();
mysqlpp::String sql("select count(*) as total from person");
query << sql;
mysqlpp::StoreQueryResult res = query.store();
cout << "has " << (*res.begin())[0] << " rows" << endl;
} catch (mysqlpp::BadQuery& e) {
cerr << "\n bad query 2>" << e.what() << endl;
cout << "\nmake database fly back now by pressing enter>" << endl;
while (!conn.ping()) {
//sleep(1);
cout << "\nwaiting for database to fly back>" << endl;
}
if (!conn.select_db(DBS)) {
cerr << "\nfailed to reconnect" << endl;
}
}
try {
mysqlpp::Query query = conn.query();
//this is how my relation and its attributes looks like
String sql("insert into person(firstname,lastname,gender,love,angry,"
"forgiving) values('joy57/qxx','crimson','male','high','medium','high');");
query << sql;
query.execute();
cerr << "\n **inserted successfully**\n" << endl;
} catch (mysqlpp::BadQuery& e) {
cerr << "bad query 3>" << e.what() << e.errnum() << endl;
return -1;
}
cerr << "Jesus helps me when i stumble and fall" << endl;
return 0;
}