I am using MSVC with Visual Studio 2013. This is the code I am compiling:
#include <iostream>
using namespace std;
void crash()
{
cout << "crash?" << endl;
system("PAUSE");
}
int main(int argc, char *argv[])
{
atexit(crash);
//while(true);
return 0;
}
The way it is right now - it works like a charm. I start the program, it goes inside the crash function, pauses, I press a key and it closes normally. All cool. However, if I uncomment the while loop and use the X button on the console to close it, I get a crash inside the endl function. I was able to determine that the crash is caused by _Ostr.widen()
This is the implementation of the endl function, provided by MSVC:
template<class _Elem,
class _Traits> inline
basic_ostream<_Elem, _Traits>&
__CLRCALL_OR_CDECL endl(basic_ostream<_Elem, _Traits>& _Ostr)
{ // insert newline and flush stream
_Ostr.put(_Ostr.widen('\n'));
_Ostr.flush();
return (_Ostr);
}
Using Ctrl+C to terminate the program causes the same effect. How can I fix this?
Seems like my suspicions turned out to be true. I modified the code like so:
#include <iostream>
using namespace std;
#include <Windows.h>
void crash()
{
printf("%i\n", GetCurrentThreadId());
system("PAUSE");
}
int main()
{
printf("%i\n", GetCurrentThreadId());
atexit(crash);
//while(true);
return 0;
}
When the program exists normally both printf()s display identical thread IDs, however when I press Ctrl+C or the X button the thread IDs are different, which explains the crash and makes a lot of sense when you think about it. Thus, here is a small example how this issue can be tackled:
#include <iostream>
#include <conio.h>
using namespace std;
#include <Windows.h>
volatile bool wantClose = false;
void OnExit()
{
cout << GetCurrentThreadId() << endl;
system("PAUSE");
}
BOOL WINAPI OnConsoleClose(DWORD dwCtrlType)
{
wantClose = true; // set a flag that the console wants us to close
ExitThread(0); // kill this thread immediately so it doesn't make the console stuck
return FALSE;
}
int main()
{
cout << GetCurrentThreadId() << endl;
SetConsoleCtrlHandler(OnConsoleClose, TRUE); // handle close requests from the console
atexit(OnExit);
while(!wantClose); // at some point in our code we will have to check whether the console wants us to close down
return 0;
}
Please note: The usage of system("PAUSE") and busy waiting are only for the sake of keeping the example simple. I do not advise their usage in real code.
Related
If I comment out the sleep_for, the program churns out commas and dots without issues. But when I add the sleep_for, it hangs for a while before suddenly writing all of the commas and dots you would have expected to come evenly during the hang all in one go.
This program was reduced to a minimum working example from something that was much larger and more complex, but fortunately the issue remains.
(Compiled using apt-installed g++ 11.2.0 on Ubuntu 20.04.4 LTS)
#include <chrono>
#include <iostream>
#include <RingBuffer.h>
#include <thread>
void writeCharToBuffer(volatile bool& quit, char, std::chrono::milliseconds);
int main()
{
bool quit { false };
using namespace std::literals;
std::thread dotToBufferThread { writeCharToBuffer, std::ref(quit), '.', 100ms};
std::thread commaToBufferThread { writeCharToBuffer, std::ref(quit), ',', 200ms};
int quitKey;
std::cin >> quitKey;
quit = true;
dotToBufferThread.join();
commaToBufferThread.join();
}
void writeCharToBuffer(volatile bool& quit, char c, std::chrono::milliseconds d)
{
while (!quit)
{
std::cout << c;
std::this_thread::sleep_for(d);
}
}
Output to std::cout is buffered.
It might be that the output without the delay will fill up the buffer quick enough that you won't notice it.
If you want immediate output you need to explicitly flush it:
std::cout << c << std::flush;
I am starting with C++ (Visual Studio 2015 and Windows 8.1), with this simple code:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
But, the output screen shows nothing!, what shall I do?
Thanks in advance.
In Visual Studio, start the program with Ctrl-F5 and it will run and pause automagically for you. No additional code needed.
Your code is perfectly fine but the program currently only prints and exits right after, because this can happen very fast you might not be able to even see it,try pausing it :
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
cin.get();
return 0;
}
Also, make sure your Anti Virus isn't blocking Visual Studio.
Your code is just fine, however, if you execute it as a cmd program, the program window will close immediately, you might not be able to even see the output. You can write extra code to solve this problem by "pausing" the program:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout << "Hello world" << endl;
system("PAUSE");
return 0;
}
if you don't like include a windows.h file every time you type, you can add a "cin.get();" in the end of the code. But to be honest, since you are just a beginner, the coolest way I think you should try, is not to use Visual Studio to learn C/C++ but to install CodeBlocks(a simple but effective IDE) to write some codes that are not so long. You know, VS is for huge and complex projects and some practical program developing.
Another solution, platform dependent. My answer is for those of you who just need test pause for debugging purposes. It's not recommended release solution!
windows
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("pause");
return 0;
}
linux (and many alternatives)
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
system("read -rsp $'Press enter to continue...\n'");
return 0;
}
Detecting paltform
I used to do this on programming homework assignments, ensuring this only happens on windows:
#include <iostream>
int main()
{
std::cout << "Hello world" << endl;
#ifdef _WIN32
system("pause");
return 0;
}
Here's a good cheatsheet for ifdef macros and operating systems: http://sourceforge.net/p/predef/wiki/OperatingSystems/
The program exits on return 0; and window closes. Before this, you must pause the program. E.g you can wait for an input.
Here is a snippet from my code to do this. It works in both windows and linux.
#include <iostream>
using std::cout;
using std::cin;
// Clear and pause methods
#ifdef _WIN32
// For windows
void waitForAnyKey() {
system("pause");
}
#elif __linux__
// For linux
void waitForAnyKey() {
cout << "Press any key to continue...";
system("read -s -N 1"); // Continues when pressed a key like windows
}
#endif
int main() {
cout << "Hello World!\n";
waitForAnyKey();
return 0;
}
Is there a way to break out of an infinite loop while it's running without using Ctrl + C? I would like to implement such a method in other programs. Like in this example program:
#include <iostream>
int main()
{
int x = 0;
for(;;)
cout << x;
}
is there a way to keep the for loop going but break it with some key at any time. I should also explain I understand using break;, but I want the loop to keep going. If I use a break condition like this, the for-loop would stop and wait for a response.
#include <iostream>
int main()
{
int x = 0;
for(;;)
{
cout << x;
if(getch()=='n')
break;
}
}
Find some condition that you wish to break out of the loop when encountered then use the break keyword:
#include <iostream>
int main()
{
int x = 0;
for(;;)
cout << x;
if(/* break condition*/){
break;
}
}
There's nothing stopping you from implementing the break condition by detecting a particular keyboard input from a user.
EDIT: From your edited question it appears you want to have loop continue running all the time and not stopping waiting for user input. The only way I can think of doing this is to spawn a new thread that listens for user input that alters a variable that gets detected in the break condition of your main thread.
If you have access to c++11 and the new thread library you could do something like this:
#include <iostream>
#include <thread>
bool break_condition = false;
void looper(){
for(;;){
std::cout << "loop running" << std::endl;
if(break_condition){
break;
}
}
}
void user_input(){
if(std::cin.get()=='n'){
break_condition = true;
}
}
int main(){
//create a thread for the loop and one for listening for input
std::thread loop_thread(looper);
std::thread user_input_thread(user_input);
//synchronize threads
loop_thread.join();
user_input_thread.join();
std::cout << "loop successfully broken out of" << std::endl;
return 0;
}
If you do decide to take a threading approach be careful as there's issues in multithreaded code that don't exist in single threaded code and they can sometimes be really nasty.
You are looking for continue I think
#include <iostream>
int main()
{
int x = 0;
for(;;)
{
cout << x;
if(getch()=='n')
continue;
}
}
I am a novice programmer working on some code for school. When the following code is executed, the word BAD is output. I do not understand why the letter C in the destructor is not output when the WriteLettersObj object is terminated.
// Lab 1
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class WriteLetters {
public:
WriteLetters();
void writeOneLetter();
~WriteLetters();
} WriteLettersObj;
WriteLetters::WriteLetters() {
cout << "B";
}
void WriteLetters::writeOneLetter() {
cout << "A";
}
WriteLetters::~WriteLetters() {
cout << "C" << endl;
}
int main() {
WriteLettersObj.writeOneLetter();
cout << "D";
getch();
return 0;
}
You are mixing iostream with non-ANSI conio.h.
Make this change:
// getch();
cin.get();
Hey presto, the C appears. At least on OS X it does. And Ubuntu.
Your program is live until you exit the main() with return 0 instruction. Since the WriteLettersObj is a global variable, it will be constructed before main() starts and destructed after main() finishes and not after getch().
To see your output getting printed, put getch() in the end of destructor.
I tried running your code without getch on linux and Mac and it runs just fine. #iammilind is right that you should move getch in the destructor.
How does one "pause" a program in C++ on Win 32, and what libraries must be included?
#include <windows.h>
Sleep(number of milliseconds);
Or if you want to pause your program while waiting for another program, use WaitForSingleObject.
In C++11, you can do this with standard library facilities:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));
If you are using boost, you can use the thread::sleep function:
#include <boost/thread/thread.hpp>
boost::system_time time = boost::get_system_time();
time += boost::posix_time::seconds(1);
boost::thread::sleep(time);
Otherwise, you are going to have to use the win32 api:
#include <windows.h>
Sleep(1000);
And, apparently, C++0x includes this:
#include <thread>
std::this_thread::sleep_for(chrono::seconds(1));
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
sleep(unsigned int)
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 second, enter 2000.
Here's an example :
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 secondes
cout << "test" << endl;
sleep(2000); // wait for 2 secondes before closing
return 0;
}
If you wait too long, that probably means the parameter is in second. So change it like that :
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting probleme, try to add of one this library on the biggining of the code.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
system("PAUSE")
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
#include <cstdlib>
cin.ignore()
The same result can be reached by using cin.ignore() :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
cin.get()
example :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
getch()
Just don't forget to add the library conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
If you wish for the program to stay responsive while "paused", you need to use a timer event.
It depends on what type of program you are writing.
A console app can just call Sleep. A GUI app probably does not want to do this, as all the menus and widgets will go insensitive, and the app won't redraw itself during this period. Instead you need to do something like set yourself up a timer with a callback when it expires.
Dont use a sleep function in your GUI if it is not provided by the framework you are working with. This could create referencing problems to data (specially in a thread that is not the main thread). This could freeze you GUI. Its not just a question of sleeping for a short time , use waitmutexes if you need to do that.