How can I do that without WIN32 API? - winapi

So, here is a countdown.
My aim is the next: if you don't do anything for the given time (ent_sec) the countdown will reach 0 after a time and return with 0, BUT if you press down the letter c (code: 99) the countdown stops and you can enter your PIN code and return with it.
I have already solved the problem with Windows.h in the next way:
if (GetAsyncKeyState(VK_SPACE))
This solves the problem is through WIN32 API (in this case you have to press SPACE, not letter 'c'), but it revealed that I can't use any WinAPI function (school project). So I rewrite this line to the following:
if (getchar() == 99)
But unfortunately it doesn't work in the proper way, cause my countdown stops in almost every second until I dont't press some "wrong" key (for example I press 'x', then the countdown goes forward, but in the next sec it stops again)... In the first solution (win func) this problem doesn't exist... So how can I fix that? Thanks. Here is the whole code of my function:
unsigned Timer::DownCount
{
int ent_sec = this.time;
cout << "The counter has started (" << this.time << "sec), press 'C' to enter your PIN code: " << endl;
while (ent_sec >= 0)
{
if (getchar() == 99) // c letter's code is 99 in ANSI (or ASCII dunno)
{
unsigned code;
cout << "PIN code: ";
cin >> code;
return code;
}
else
{
SecCounter(1); // this function counts 1 secundum
cout << ent_sec << endl;
ent_sec--;
}
}
return 0;
}

I don't believe there's a standard way to do this that will work across all platforms, but here's one way of doing it that will work on Windows without actually using Windows API functions.
int getch_nowait()
{
if (!kbhit()) return -1;
return getch();
}
Then your check just becomes if (getch_nowait() == 99) ...
This code may be compiler specific. If it doesn't work for you, it'll help if you tell us what compiler and operating system you are using.

Related

C++ empty() and all_of() for checking string is empty or have only digit

I'm creating an IO console application and at the inputs i got an 'while' loop with two condition
empty() and all_of(), the function all_of() seems to work properly but when i press enter the empty() function not working and just let me to input the next thing in the 'struct'. I'm not sure am i doing it correct..There is the part of the code
cout << "Enter age: ";
getline(cin, age_str);
while(!age_str.empty() && !all_of(age_str.begin(), age_str.end(), ::isdigit)){
cout << "--Please Enter an integer-- " << endl;
cin.clear();
getline(cin, age_str);
}
stringstream(age_str) >> person_arr[n].age;
There are a link to the full code : enter link description here
The logic of the conditional of the while is incorrect.
What you need to do is:
If the line is empty, get the next line.
If the line is not empty and the line has anything other than digits, get the next line.
!age_str.empty() && !all_of(age_str.begin(), age_str.end(), ::isdigit) does not do that.
You need to use age_str.empty() || (!all_of(age_str.begin(), age_str.end(), ::isdigit))
I always recommend, when in doubt, simplify.
while ( !is_input_valid(age_str)) )
{
...
}
where
bool is_input_valid(std::string const& input)
{
if ( input.empty() )
{
return false;
}
return std::all_of(input.begin(), input.end(), ::isdigit);
}

how to exit a std::execution::par_unseq loop based on a condition

I need to exit the loop, if one of my queue elements satisfies a condition. putting break results in a compile error. what is the best way to execute the loop parallel
//code
std::deque<element> my_elements;
std::for_each(std::execution::par_unseq, my_elements.begin(), my_elements.end(),
[&](auto v) {
if (v.attribute == something)
{
break;
}
});
I'm pretty sure that won't work. Why? because break is a statically scoped operation; i.e, the destination for the break is determined at compile time. Putting it into a lambda (w the loop external to the lambda) makes it impossible for the compiler to see where to "break to".
Example w/o parallelism:
vector<int> v {1,2,3,4,5,6,7,8,9};
std::for_each(v.begin(), v.end(),
[](int i) { cout << i << ' '; if (i == 5) break; });
cout << endl;
gives me the following error:
so.cpp:10:45: error: 'break' statement not in loop or switch statement
[](int i) { cout << i << ' '; if (i == 5) break; });
To answer your question; I don't think there's a good way to break out of for_each in a parallel algorithm. For the non-parallel case, you could throw an exception, but that won't work in the parallel case.

OpenCV works slow in Microsoft Visual Studio Community 2017

I am trying to work with webcam using C++ and OpenCV in Microsoft Visual Studio Community 2017, but it works very slow(I can't see any changes in video - only one frame). Although the same functions work fine in Python. How can I solve this problem? Thanks.
Mat frame;
VideoCapture vid(0);
if (!vid.isOpened())
{
return -1;
}
else {
while (vid.read(frame))
{
imshow("Video", frame);
if (waitKey() >= 0)
{
break;
}
}
}
return 0;
The problem is the condition waitKey() >= 0.
Change the code to:
Mat frame;
VideoCapture vid(0);
if (!vid.isOpened())
{
return -1;
}
else {
while (vid.read(frame))
{
imshow("Video", frame);
int key = waitKey(1);
if (key == 27)
{
break;
}
}
}
return 0;
waitKey waits the specified time (1) for a key press. In this example we store the value in "key" and if it matches the ascii value 27 (esc key) the program ends.
Why your code does not work:
Your program doesn't seem to work because using waitKey() in C++ it is interpreted as waitKey(0) which will wait forever until some key is pressed (0 means infinite waiting). And when a key is pressed the if sentence (>=0) will become true (because the ascii value of the key pressed will be greater or equal than 0), so the program will exit.

OMNeT++: Different results in 'fast' or 'express' mode

Used Versions: OMNeT++ 5.0 with iNET 3.4.0
I created some code, which gives me reliable results in ‘step-by-step’- or ‘animated’ simulation mode. The moment I change to ‘fast’ or ‘express’ mode, it gets buggy. The following simplified example will explain my problems:
void MyMacSlave::handleSelfMessage(cMessage *msg)
{
if (msg == CheckAck) {
std::cout << “CheckAck: “ << msg << std::endl;
}
if (msg == transmissionAnnouncement) {
std::cout << “transmissionAnncouncement: “ << msg << std::endl;
}
if (msg == transmissionEvent) {
std::cout << “transmissionEvent: “ << msg << std::endl;
}
delete msg;
}
There is a function, which is called for handling self-messages. Depending on what self-message I got, I need to run different if queries.
I get this correct output in step-by-step or animated mode:
CheckAck: (omnetpp::cMessage)CheckAck
transmissionAnncouncement: (omnetpp::cMessage)transmissionAnncouncement
transmissionEvent: (omnetpp::cMessage)transmissionEvent
And this is the strange output I get using fast or express mode:
CheckAck: (omnetpp::cMessage)CheckAck
transmissionAnncouncement: (omnetpp::cMessage)transmissionAnncouncement
transmissionAnncouncement: (omnetpp::cMessage)transmissionEvent
transmissionEvent: (omnetpp::cMessage)transmissionEvent
The third output line shows that the self-message is ‘transmissionEvent’, but the ‘if (msg == transmissionAnnouncement)’ is mistakenly considered as true as well.
As shown above I get different simulation results, depending on the simulation mode I am using. What is the reason for the different output? Why is there even a difference?
As Christoph and Rudi mentioned there was something wrong with the memory allocation. When a pointer is de-allocated and a new one is allocated on the same memory, there will be something wrong. The difference regarding the usage of different running modes is just a sign that there are errors to that effect.
In my case it was useful to check for message-kinds like:
if (msg->getKind() == checkAckAckType) {
instead of the method used in the originally question. I defined the message-kinds using simple enums.

C++11 std::condition_variable - notify_one() not behaving as expected?

I don't see this program having any practical usage, but while experimenting with c++ 11 concurrency and conditional_variables I stumbled across something I don't fully understand.
At first I assumed that using notify_one() would allow the program below to work. However, in actuality the program just froze after printing one. When I switched over to using notify_all() the program did what I wanted it to do (print all natural numbers in order). I am sure this question has been asked in various forms already. But my specific question is where in the doc did I read wrong.
I assume notify_one() should work because of the following statement.
If any threads are waiting on *this, calling notify_one unblocks one of the waiting threads.
Looking below only one of the threads will be blocked at a given time, correct?
class natural_number_printer
{
public:
void run()
{
m_odd_thread = std::thread(
std::bind(&natural_number_printer::print_odd_natural_numbers, this));
m_even_thread = std::thread(
std::bind(&natural_number_printer::print_even_natural_numbers, this));
m_odd_thread.join();
m_even_thread.join();
}
private:
std::mutex m_mutex;
std::condition_variable m_condition;
std::thread m_even_thread;
std::thread m_odd_thread;
private:
void print_odd_natural_numbers()
{
for (unsigned int i = 1; i < 100; ++i) {
if (i % 2 == 1) {
std::cout << i << " ";
m_condition.notify_all();
} else {
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock);
}
}
}
void print_even_natural_numbers()
{
for (unsigned int i = 1; i < 100; ++i) {
if (i % 2 == 0) {
std::cout << i << " ";
m_condition.notify_all();
} else {
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock);
}
}
}
};
The provided code "works" correctly and gets stuck by design. The cause is described in the documentation
The effects of notify_one()/notify_all() and
wait()/wait_for()/wait_until() take place in a single total order, so
it's impossible for notify_one() to, for example, be delayed and
unblock a thread that started waiting just after the call to
notify_one() was made.
The step-by-step logic is
The print_odd_natural_numbers thread is started
The print_even_natural_numbers thread is started also.
The m_condition.notify_all(); line of print_even_natural_numbers is executed before than the print_odd_natural_numbers thread reaches the m_condition.wait(lock); line.
The m_condition.wait(lock); line of print_odd_natural_numbers is executed and the thread gets stuck.
The m_condition.wait(lock); line of print_even_natural_numbers is executed and the thread gets stuck also.

Resources