Applications keeps closing vs 2012 - c++

My application keeps closing when debugging. I'm not able to view what the "results" are since it goes too fast.
I've been looking at many different forums and topics and all the solutions given just wont apply. I've tried different commands before returns 0; etc and also changing an option in the project.
I'm just starting and trying to learn from the c++ primer but this is frustrating me already :).
Following is my code, please help!
#include <iostream>
int main ()
{
int sum = 0, val = 1;
while (val <= 10) {
sum +=val;
++ val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
Console.Read();
return 0;
}

Don't do Console.Read();, do std::cin.get();.

Try this:
#include <iostream>
int main ()
{
int sum = 0, val = 1;
while (val <= 10) {
sum +=val;
++ val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
std::cin.get(); // hackish but better than system("PAUSE");
return 0;
}

Assuming that you are using Visual Studio:
Debug builds will run until they hit a breakpoint or until the program finishes (which ever comes first). If the program finishes, the console closes. Place a break point on the line containing return 0; and your console will stay open until you click Continue.
Release builds will run until the program finishes. If the program finishes, you will be prompted to Press any key to continue. . . and the console will stay open.
If you are not setting breakpoints in such a small program, you are wasting your resources -- debug mode will impact the performance of the program.
Thus, you should build in Release mode and forget about using std::cin.get().

Related

How to count the times a key has been pressed in c++

I am making a game in Visual studious 2017 (visual c++), where you have to repeatedly press the space bar to earn money. But I have run into a problem, the compiler can't keep up when you press the spacebar really fast and so It miscounts. I tried doing some research, but all I got was this and as I said earlier it cant keep up.
this is so far what i got:
int click_systm()
{
char spacebar;
while (1)
{
if (GetAsyncKeyState(VK_SPACE) != 0)
{
if (GetKeyState(VK_SPACE) == 0)
{
spacebar = _getch();
int value = spacebar;
if (value == 32)
{
money++;
cout << money << endl;
}
}
}
}
}
If you made it here, thanks for taking your time to read this :)
The compiler is what compiles your C++ code into some binary. The CPU as well as the OS should be able to keep up with a human speed spacebar smashing. The problem can be from the fact that you run your soft inside a console(please see the comment left by user253751).
std::cout slows down a program by a lot because of the time it takes to print. As also mentioned it the comment, split your printing in a different thread. You can also add std::ios_base::sync_with_stdio(false); to gain some speed if you really need to.
I have found an answer to my own question, for those that have the same problem. This code here will do the same thing but is more responsive and will keep up to the button mashing.
int click_systm()
{
char spacebar;
while (1)
{
spacebar = _getch();
if (spacebar == 32)
{
money++;
cout << money << "\n";
}
}
}
Thanks to everyone trying to help me, espically MrScriptX and Antonio.

Severe & Bizzare performance issue

Update
Ok, I removed the 3 couts and replaced it with *buffer = 'a', and there was a big performance difference. Removing that line made the program 2x as fast. If you go on godbolt and compile it using msvc, that single line of code changes most of the program. (It adds a whole lot more complexity)
The following might seem extremely weird, but it's true on my computer:
Alright, so I was doing some benchmarking of some code, and I noticed extremely weird performance anomalies that were 100% consistent. I'm running windows-10 and visual-studio-2019. Basically, deleting a line of code that is never called completely changes the performance of the program.
Here is exactly what to do:
Create new VS-2019 Console C++ App project
Set the configuration to Release & x64
Paste the code below:
#include <iostream>
#include <chrono>
class Test {
public:
size_t length;
size_t doublingVal;
char* buffer;
Test() : length(0), doublingVal(2) {
buffer = static_cast<char*>(malloc(1));
}
~Test() {
std::cout << "called" << "\n";
std::cout << "called" << "\n";
std::cout << "called" << "\n"; // Remove this line and the time decreases DRASTICALLY (ie remove line 14)
}
void append() {
if (doublingVal == length) {
doublingVal <<= 1;
}
*buffer = 'a';
++length;
}
};
int main()
{
Test test;
auto start = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < static_cast<size_t>(1024) * 1024 * 1024 * 4; ++i) {
test.append();
}
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count() << "\n";
}
Run the program using CTRL+F5, not in debug. Now remember how long it takes to run. (a few seconds)
Then, in the destructor of Test, remove the third line which has the comment.
Run the program again, and you should see that the performance increases drastically. I tested this exact same code with 4 different projects all brand new, and 3 different computers.
The destructor is called at the very end, when the entire program is finished measuring time. The extra cout shouldn't affect anything.
Edit:
You can also see a similar thing go on if you remove the 3 cout's and replace it with a single *buffer = 'a'. Then CTRL+F5 once again, record the time, and then remove that line we just added. Then run it again and the time magically decreases by half.
WTF is going on, and how do you solve the weird performance difference?

How to use boost::async_system?

I am quite new to boost, as well as to multithreading and launching application using libraries. For my desired funcitonality, I was recommended by colleague to use boost::process library.
But the documentation to this part of boost is quite insufficient, so I could not determine which function suits my task best by documentation. I therefore started to try several functions there, but non has all the desired properties.
However there is one I cannot figure out, how to properly use. I cannot even compile it, let alone run it. And the function is boost::process::async_system. I could not find anywhere on internet some step-by-step guide on how to use this function and what individual components mean and do.
Could someone explain to me in detail the individual arguments and template arguments of the function ? Or provide a link to a detailed manual?
I like the examples here: https://theboostcpplibraries.com/boost.thread-futures-and-promises
For example, look at example 44.16, they clearly show how to use async:
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
#include <iostream>
int accumulate()
{
int sum = 0;
for (int i = 0; i < 5; ++i)
sum += i;
return sum;
}
int main()
{
boost::future<int> f = boost::async(accumulate);
std::cout << f.get() << '\n';
}
Waiting happens at the get method, not before. You might use a non-waiting mechanism, too.
As for compiling, you need to first build boost. Building is explained in detail here: https://www.boost.org/doc/libs/1_62_0/more/getting_started/windows.html
Most parts of the library work header-only. For asio, building the binary libraries (also explained in the link) is necessary. In your project (i.e. visual studio projects, xcode project or just some make files), you need to set include and library headers of boost to use it. The link above helps with this as well.
I'm just ramping up on Boost.Process but the sample code I have working might be helpful here.
boost::process:async_system() takes 3 parameters: a boost::asio::io_context object, an exit-handler function, and the command you want to run (just like system(), and it can be either a single line or more than one arg).
After it's invoked, you use the io_context object from the calling thread to manage and monitor the async task - I use the run_one() method which will "Run the io_context object's event processing loop to execute at most one handler" but you can also use other methods to run for a duration etc.
Here's my working code:
#include <boost/process.hpp>
#include <iostream>
using namespace boost;
namespace {
// declare exit handler function
void _exitHandler(boost::system::error_code err, int rc) {
std::cout << "DEBUG async exit error code: "
<< err << " rc: " << rc <<std::endl;
}
}
int main() {
// create the io_context
asio::io_context ioctx;
// call async_system
process::async_system(ioctx, _exitHandler, "ls /usr/local/bin");
std::cout << "just called 'ls /usr/local/bin', async" << std::endl;
int breakout = 0; // safety for weirdness
do {
std::cout << " - checking to see if it stopped..." << std::endl;
if (ioctx.stopped()) {
std::cout << " * it stopped!" << std::endl;
break;
} else {
std::cout << " + calling io_context.run_one()..." << std::endl;
ioctx.run_one();
}
++breakout;
} while (breakout < 1000);
return 0;
}
The only thing my example lacks is how to use boost::asio::async_result to capture the result - the samples I've see (including here on slashdot) still don't make much sense to me, but hopefully this much is helpful.
Here's the output of the above on my system:
just called 'ls /usr/local/bin', async
- checking to see if it stopped...
+ calling io_context.run_one()...
- checking to see if it stopped...
+ calling io_context.run_one()...
VBoxAutostart easy_install pybot
VBoxBalloonCtrl easy_install-2.7 pyi-archive_viewer
((omitted - a bunch more files from the ls -l command))
DEBUG async exit error code: system:0 rc: 0
- checking to see if it stopped...
* it stopped!
Program ended with exit code: 0

Do while loops stop verifying after condition isn't met anymore?

I have recently started learning c++ and I have a question regarding the last section I reached, the while loop one.
In this code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
return 0;
}
will the while command continue checking if i <=5 after the value goes over 5 or will it stop?
If I was making a program and changed the value of i down the line to one that meets the condition of the loop would it start again or would I have to rewrite the loop code again?
Thanks in advance for the answers!
edit: Thanks for your answers and comments. I tried putting into code what I was thinking and I noticed that changing the value of i after the loop didn't make it start again(meaning that it had already stopped checking after i surpassed 5).
I realize it was a stupid question that I could have simply solved by trying to put it into code, but I still asked for answers just to be sure. Thanks again!
If you changed i to 0 after the loop has ended like this:
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
i=0;
return 0;
}
The loop wouldn't start again because it would just set i to 0 and then go to return 0. Once the loop is executed it won't be run again.
Note that C++ executes the code sequentially, this means that its goes through every line, executes it, then goes to the next one. This is confusing for loops because you see previous code being executed again; therefore, to solve this dilemma, think of the loop segment as a block, once this block executes, the normal sequential execution continues.
For Future reference: C++ has a beautiful feature called Multi-threading, where you can allow several code to execute in a parallel fashion. You will meet this feature sometime in the future.

conditional display in gdb

I'm using gdb to debug some c++ code. At the moment the code I'm looking at iterates through an array of pointers, which are either a pointer to some object or a NULL pointer.
If I just display list[index]->member it'll complain when list[index] is null. Is there anyway to display the member only if list[index] is not null? I know you can set conditional breakpoints (condition <bp-num> <exp>) but I'm not sure how that'd help.
The code in question is:
for (int i=0;i<BSIZE*BSIZE;i++){
if (vms[i]==target) {valid=true; break;}
}
where vms is the array of pointers.
Since display accepts arbitrary expressions, you can try something like the following display command:
display (list[index]) ? list[index]->member : "null"
I'm not sure if that cleans things up well enough for what you want - you'll still get a display, but it won't be a complaint.
Basically the condition works like this:
#include <iostream>
int main() {
for (int i=0; i<10; ++i) {
std::cerr << i << std::endl;
}
}
You can debug it like this:
(gdb) break 5
Breakpoint 1 at 0x100000d0e: file foobar.cpp, line 5.
(gdb) condition 1 i==3
(gdb) r
Starting program: /private/tmp/foobar
Reading symbols for shared libraries ++. done
0
1
2
Breakpoint 1, main () at foobar.cpp:5
5 std::cerr << i << std::endl;