Someone can tell me what is wrong with this code?
I want to show 'a' with 200ms delay
eg. number 3 will show after 200ms
numbers 2 and 1 the same, but I can't write correct code to do this.
#include <iostream>
#include <cstdlib>
#include <string>
#include <windows.h>
using namespace std;
int main() {
int a=3;
do {
cout<<a<<endl;
a-=1;
string tekst = a;
for (int i = 0; i < tekst.length(); i++) { // Czasowe pokazanie napisu//
cout << tekst[i];
cout << tekst[i];
Sleep(200);
}
}
while (a=1);
getch();
}
I want to show 'a' with 200ms delay eg. number 3 will show after 200ms numbers 2 and 1 the same, but I can't write correct code to do this.
In that case, your Sleep is misplaced since it's placed after printing. You also do not need to convert the int to a std::string before printing it. ints are perfectly streamable out of the box.
Your do-while loop is also wrong. while (a=1); assigns the value 1 to a so the loop will go on forever since 1 will be implicitly converted to true.
A portable way to sleep 200 ms would be using the std::this_thread::sleep_for() function instead of Sleep() which is not a standard function.
It could look like this:
#include <chrono> // std::chrono::milliseconds
#include <iostream>
#include <thread> // std::this_thread::sleep_for
using namespace std::chrono_literals;
int main() {
for(int a=3; a>0; --a) {
// sleep for 200 ms, the standard way
std::this_thread::sleep_for(200ms);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
Update for old versions of Dev C++ that doesn't support <thread> and <chrono>:
#include <iostream>
int main() {
for(int a=3; a>0; --a) {
Sleep(200);
std::cout << a << std::flush;
// or: std::cout << a << '\n';
}
}
Related
This question already has answers here:
Using scanf/printf to input into/output from a bitset
(3 answers)
Closed 5 months ago.
#include <bitset>
#include <assert.h>
#include <stdio.h>
using namespace std;
int main()
{
bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
assert(bs[12]==1);
printf("bs[11]=%d\n", bs[11]);
printf("bs[12]=%d\n", bs[12]);
return 0;
}
console output:
Why can't I simply get 0 or 1 as output ?
printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference.
You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console):
#include <bitset>
#include <assert.h>
#include <iostream>
int main()
{
std::bitset<128> bs(42);
bs[11] = 0;
bs[12] = 1;
assert(bs[12] == 1);
std::cout << "bs[11]=" << bs[11] << std::endl;
std::cout << "bs[12]=" << bs[12] << std::endl;
return 0;
}
Output:
bs[11]=0
bs[12]=1
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
With some review comments :
#include <cassert>
#include <bitset>
#include <iostream>
// anything with a .h extension is probably "C" not "C++"
// #include <assert.h>
//#include <stdio.h>
// using namespace std; <== NO, don't use using namespace std;
int main()
{
std::bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
assert(bs[12]==1);
std::cout <<"bs[11]" << bs[11] << "\n";
std::cout << "bs[12]" << bs[11] << "\n";
return 0;
}
If you are using C++ then don't call printf to output something (my compiler refuse to compile your code correctly).
This C++ code works correctly using iostream:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<128> bs(42);
bs[11]=0;
bs[12]=1;
std::cout << "bs[11]=" << bs[11] << std::endl;
std::cout << "bs[12]=" << bs[12] << std::endl;
return 0;
}
I am writing code that terminates by entering e or t , and I want everything to work under two minuets, but I cant get things to work once I include the delay or sleep, tried using the chrono lib
int main()
{
string ee;
int x=5, y=3;
while (true) {
std::cout <<y<< std::endl;
cout <<x<< std::endl;
cin >>ee;
if (ee =="e" { break;}
if (ee =="e" { break;}
if (ee =="E" { break;}
if (ee =="T" { break;}
}
}
The elaborate on my comment above:
There is no standard c++ function to limit the runtime of a program as such. You'll need to implement such a mechanism, according to your specific needs.
My solution below assumes that you do not intend to abort the std::cin operation (cin >>ee;). I assumed that the usage of std::cin was just to simulate some way of breaking a long iterative process.
If this is the case, you can do get a time measurement before the long process. Then in each iteration get a new time measurement and exit it if your maximum time elapsed.
Something like the following:
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
int x = 5, y = 3;
auto tStart = std::chrono::steady_clock::now();
while (true) {
auto tNow = std::chrono::steady_clock::now();
auto elapsedSecs = std::chrono::duration_cast<std::chrono::seconds>(tNow - tStart).count();
if (elapsedSecs >= 120)
{
// 2 minutes or more passed => exit
break;
}
// Simulate one iteration of the long process:
std::cout << y << std::endl;
std::cout << x << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
Note: it's better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
I am trying to create a sine, cosine, tangent, and cotangent table. I want to printf/cout an "INF" instead of huge complicated numbers or interesting symbols when I calculate the cotangent of 0. But it doesn't allow me to do this. I tried every way I can think of, but I couldn't do it.
Can you help me about that?
Code is below:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <iostream>
#define PI 3.14159265
#include <math.h>
#include <string>
#include <sstream>
using namespace std;
int main()
{
setlocale(LC_ALL, "Turkish");
string diziBaslik[1][5] = {{"AÇI","SİN","COS","TAN","COTAN"}};
string diziBaslikCizgi[1][5] = {{"------","------","------","------","------"}};
float dizi[10][5] = {
{0 ,sin(0*PI/180) ,cos(0*PI/180) ,tan(0*PI/180) ,1/tan(0*PI/180) },
{10,sin(10*PI/180),cos(10*PI/180),tan(10*PI/180),1/tan(10*PI/180)},
{20,sin(20*PI/180),cos(20*PI/180),tan(20*PI/180),1/tan(20*PI/180)},
{30,sin(30*PI/180),cos(30*PI/180),tan(30*PI/180),1/tan(30*PI/180)},
{40,sin(40*PI/180),cos(40*PI/180),tan(40*PI/180),1/tan(40*PI/180)},
{50,sin(50*PI/180),cos(50*PI/180),tan(50*PI/180),1/tan(50*PI/180)},
{60,sin(60*PI/180),cos(60*PI/180),tan(60*PI/180),1/tan(60*PI/180)},
{70,sin(70*PI/180),cos(70*PI/180),tan(70*PI/180),1/tan(70*PI/180)},
{80,sin(80*PI/180),cos(80*PI/180),tan(80*PI/180),1/tan(80*PI/180)},
{90,sin(90*PI/180),cos(90*PI/180),tan(90*PI/180),1/tan(90*PI/180)}
};
cout << diziBaslik[0][0] << "\t";
for(int j=1;j<5;j++){
cout << diziBaslik[0][j] << "\t\t";
}
cout<< endl;
cout << diziBaslikCizgi[0][0] << "\t";
for(int j=1;j<5;j++){
cout << diziBaslikCizgi[0][j] << "\t\t";
}
cout << endl;
for(int i=0;i<10;i++){
for(int j=0;j<5;j++){
if(j==0){
cout << dizi[i][j] << "\xB0\t";
}
else{
printf("%.6f\t", dizi[i][j]);
}
}
cout<<endl;
}
}
There are 2 issues:
Due to low PI precision, tan(90*PI/180) returns a large number and not infinity.
Your system is printing infinity as 1,#INF00. I don't think there's a way to change that.
To work around both issues don't let large values go to printf and instead print your own string if the value is larger than some tolerance value:
if (dizi[i][j] < 1e5) {
printf("%.6f\t", dizi[i][j]);
} else {
printf("INFINITY\t");
}
Also note that setlocale() won't affect cout because it's constructed before. For cout you need to add something like
cout.imbue(std::locale("Turkish"));
I want to make a c++ program that runs a while loop for a defined amount of time and then exits the loop.
Having the loop doing some stuff while running and when the time set is reached it will break out of the loop. For example have the while the loop is running it will keep printing stuff on the screen and when 1 minute has passed it will exit the loop.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
time_t now = time(nullptr);
tm* current_time = localtime(&now);
int current_minute = current_time->tm_min;
int defined_minute = current_minute + 1;
while (current_minute < defined_minute)
{
current_minute = current_time->tm_min;
}
}
I created this code and it was supposed to work but it doesn't, I tried to debug but I still don't understand why it doesn't work.
P.S. this is my first time posting a programming problem online, appreciate if someone tells me how to better put my problems in the future.
Here is the simplest answer:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto finish = system_clock::now() + 1min;
do
{
cout << "stuff\n";
} while (system_clock::now() < finish);
}
This requires C++14 or C++17. If you're using C++11, substitute minutes{1} for 1min. If you're using C++03, <chrono> is not available, and you'll have to use the C API for timing, which is significantly harder to use.
Here is a video tutorial on <chrono>.
Use #include <chrono>
auto t0 = std::chrono::system_clock::now();
while ( (std::chrono::system_clock::now()-t0) < std::chrono::minutes{1})
{
// do stuff
}
This snippet of code needs C++11 at least and may count somewhat complex C++ objects but here is how I imaginated it
#include <iostream>
#include <future> //std::async
#include <atomic>
#include <chrono>
#include <sstream>
int main()
{
int i = 0;
std::stringstream sstr;
std::atomic<bool> do_it(true);
//store future so that async returns immediately
//see Notes paragraph on https://en.cppreference.com/w/cpp/thread/async
auto fut = std::async(std::launch::async, [&do_it]() {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
do_it = false;
});
//Preemtion could steal some time here...
while ( do_it )
{
sstr << "Iteration: " << ++i << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::cout << sstr.str() << "\n" << std::flush;
std::cout << "Bye\n" << std::flush;
}
The result is ( you can try it on online C++ compiler like coliru)
Iteration: 1
...
Iteration: 95
Iteration: 96
Iteration: 97
Iteration: 98
Bye
Hope it helps
Another answer could be the use of condition variable in order to cope with the ugly sleep_for(...) often used like in my first answer leading to only 98 iterations instead of 100 because of the time taken by the application/calculations ( here printing some loop number inside a stringstream ).
Condition Variables can target more than 1 thread
#include <iostream>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <chrono>
#include <sstream>
//From https://en.cppreference.com/w/cpp/thread/condition_variable/wait_until
int index[2] = { 0 };
std::stringstream sstr;
std::condition_variable cv;
std::mutex cv_m;
std::atomic<bool> do_it(true);
std::mutex mut_print;
void foo(char id, int * index)
{
if ( ! index ) return;
auto new_tp = std::chrono::system_clock::now();
while ( do_it )
{
{
std::lock_guard<std::mutex> lock(mut_print);
sstr << "Iteration of "<< id << ": " << ++(*index) << "\n";
}
new_tp += std::chrono::milliseconds(10);
while ( do_it )
{
std::unique_lock<std::mutex> lk(cv_m);
if(std::cv_status::timeout == cv.wait_until(lk,new_tp ) ) {
break;
}
}
}
}
void signals()
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
do_it = false;
cv.notify_all();
}
int main()
{
std::thread t1(foo,'A',&index[0]),t2(foo,'B',&index[1]),ts(signals);
t1.join();
t2.join();
ts.join();
std::cout << sstr.str() << "\n" << std::flush;
std::cout << "Bye\n" << std::flush;
}
coliru
Result is
Iteration of A: 1
Iteration of B: 1
Iteration of A: 2
Iteration of B: 2
...
Iteration of A: 100
Iteration of B: 100
Iteration of A: 101
Iteration of B: 101
Bye
This time we went a little bit to far with 101 iterations but this example does not pretend to execute a limited/given number of times
i'm having problem with this code :
#include <iostream>
#include <math.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <stdio.h>
using std::cout; using std::cerr;
using std::cin; using std::string;
using std::endl;
int main(int argc,char* argv[])
{
for(int x = 0; x <= 2013; x++)
{
cout << "Iteration: "<< x << "\r";
cout << "";
}
return 0;
}
i need my code to print "Iteration: 0" and than just refresh that 0 to 1,2,3,4.... everything on one console line. I used the carriage return but it doesn't work,the line are printed one after another as when i use "\n". The enviroment is linux 64 bit. The IDE is eclipse 8.01.
You have to put it at the beginning of the line:
cout << "\rIteration: "<< x;
EDIT: I have tested this modification of the original OP's code and it prints what he wants. Also, Oh dear look what I've found.
Also, as suggested by #Wintermute, you can do the following inside the for loop, for better visualization:
cout << "\rIteration: "<< x << std::flush;
sleep(1);