Reputation: 61
A C++ program that perform such:
cout<<"Hello please enter in your age: ";
int age;
cin>>age;
While the system waits for input, I want to display this following loop:
for(;;)
{
cout << "Waiting.............." << '\r' << flush; Sleep(500);
cout << ".......Waiting......." << '\r' << flush; Sleep(500);
cout << "..............Waiting" << '\r' << flush; Sleep(500);
}
The loop should stop when there is any input.
Upvotes: 1
Views: 2973
Reputation: 1092
Because the cin
and read functions in general are blocking operation, you cannot make something else because your main thread is "blocked".
The only way for doing this is to create another thread which will print to the same STDOUT controlled by a global variable. Basically you need something like:
//print thread
while(global == 1)
{
cout<<"TEXT";
........
}
and in the main thread:
volatile int global = 0;
....
global = 1;
cin>>age;
global = 0;
This is not a good practice but you can start with this but try to use a MUTEX instead of the global variable
Upvotes: 1
Reputation: 1212
This worked for me
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void *PrintWaiting(void *id)
{
for(;;)
{
cout << "Waiting.............." << '\r' << flush; sleep(1);
cout << ".......Waiting......." << '\r' << flush; sleep(1);
cout << "..............Waiting" << '\r' << flush; sleep(1);
}
pthread_exit(NULL);
}
int main ()
{
pthread_t thread;
pthread_create(&thread, NULL, PrintWaiting, NULL);
int age;
cout << "Hello please enter in your age: ";
cin >> age;
pthread_cancel(thread);
cout << age << endl;
pthread_exit(NULL);
}
compile with -lpthread
flag.
It'll look strange, you have to figure out how to format the output
Upvotes: 1