c++ Print on same line - c++

I am using a chrono to get the time elapsed during a loop. I would like to display this time every loop run.
I can do this:
for(int i = 0;i<3;i++)
{
sleep(2 secs);
time= get_time();
cout<<"time is : "<<time;
}
But I have the output:
time is : 2 time is : 4 time is : 6
I could add an endl to have it in column but that is not what I want. My loop is about million times, so I don't really want to print a million lines.
I would just like to print like:
time is : 2
and then refresh it to
time is : 4
and so on. Is there a way to do this?

You can use endl with clrscr() .

printing to terminals is very easy, but it can be extremely hard at the same time. At its core, a terminal is simply a file, that you can use to write or read on. Performing tasks such as changing cursor's position is in fact system-specific and your code will have to be platform dependent.
But don't panic! People have done it before and even wrote libraries to do it. I think NCurses will do the job. https://www.gnu.org/software/ncurses/ncurses.html
I advice you to refer to this thread to see some issue related to your question: How to clear a specific line with NCurses?
I have never used ncurses my self, so I wish you best of luck!
Enjoy programming!

Related

How do you make RPG-like scrolling text? C++ on Linux

I'm a beginner coder making a simple text 'choose your own adventure' game, but I want it to scroll out the text like an RPG instead of just spitting out the text. How can I do that?
I believe that the ncurses library is exactly what you are looking for. It allows you lower access to the terminal text, to produce things like full screen text, like this:
A tutorial for how to use it can be found here, and you can download version 6.3 here.
It is used in many applications, like GNU nano. A full list of applications using ncurses can be found here.
I'm going to assume you're just supposed to write to a console.
std::string str = "Your text";
for(char& current_char : str) {
std::cout << current_char << std::flush;
sleep(1000);
}
std::cout << std::endl;
The for loop is going to iterate over each character in the string.
It will then output it to cout. std::flush is here to force the output to be update without using std::endl which would return carriage and we don't want that.
sleep will pause for an amount of time in milliseconds, here 1000 milliseconds (1 second). Be careful though; sleep is a Windows function. On Linux, use usleep. If you need it to be cross-platform you should probably use the thread sleeping functions or make something yourself with chrono.
And finally, we use std::endl to return carriage and update the output.

QProcess How to deal with too much input?

I'm using 3 command line tools via QProcesses to play music on my Linux (Mint) desktop via the Jack server. It's all working very well, but the input from one of the tools 'jack_showtime' arrives at about 12,000 lines per second.
I only need to see one line every 0.1 seconds, but the only way I've found to get a full recent line is like:
j_s->readAll(); // j_s is the jack_showtime QProcess
waitAbit(20); // a 20 mS delay
QString aShowtimeLine = j_s->readLine();
aShowtimeLine = j_s->readLine();
What would be a better way to deal with so much unwanted input? It seems that; without the readAll, a line will be much too old. Without the delay, I get a blank line and without the two readLines I get part of a line.
I'd also be interested in a Bash script that could absorb most of the input, or similar.
I suggest something like this, such that no matter how fast or how slow you get input from the child process, you always use the only most recent value, every 100mS:
// at startup or in your class constructor or wherever
connect(j_s, SIGNAL(readyRead()), this, SLOT(ReadDataFromJack()));
connect(&_myQTimer, SIGNAL(timeout()), this, SLOT(UseOneLine()));
_myQTimer.start(100);
void MyClass :: ReadDataFromJack()
{
while(j_s->canReadLine())
{
char buf[1024];
qint64 bytesRead = j_s->readLine(buf, sizeof(buf));
if ((bytes > 0)&&(CanParseText(buf))
{
this->_mostRecentResult = ParseText(buf);
}
}
}
void MyClass :: UseOneLine()
{
printf("100mS have elapsed, time to use _mostRecentResult=%i for something!\n", this->_mostRecentResult)
}
(Note that CanParseText(buf) and ParseText(buf) above are imaginary placeholders for whatever code you use to parse ASCII text coming from your child process into data to be used by your program)
Bulls eye! Thank you. You seem to know what I already had, so it was easy to add the bits I didn't have. Mainly the limited size buffer and, as I've never seen a line longer than 79 characters, I reduced it to 100. I may have been on the right track, while looking for a script solution, when I tried to use 'stdbuf', but dealing with it all in my program is much better.
Lines received are easy to parse. I only want the first number (which can be as low as zero) from something like this:
frame = 293532731 frame_time = 114978548 usecs = 2421437949 state: Rolling
I use the following, which seems reasonably minimal:
QString recentLine = QString::fromLocal8Bit(buf);
recentLine.remove(0,8);
recentLine.chop(recentLine.length() - recentLine.indexOf(" "));
int numSamples = recentLine.toInt();
I put a counter in the ReadDataFromJack() class and see between 2,000 and 3,000 visits per 100mS!
The number represents the position of the 'play head' in samples (at 48k per second) and wont exceed the integer range in Qt, but I see you use a qint64 (long long) in your example. Should I do the same for my number?
Sorry it's an answer (and a further question), but it's too long for a comment.

Is it possible to mark tests as taking long time in googletest runs

Most of my tests finish quickly, the time taken is unnoticeable. But a few of them take a few seconds. I would like to print a hint to the user:
TEST(something, thing) {
std::cout << "This might take a few seconds\n";
ASSERT_EQ(expected_result, long_computation());
}
This doesn't blend in well with what is printed. Is there a feature for this in googletest? I couldn't find anything related. Any way to make goggliest understand it, print a hint to the user, and even report error in case the test runs too long? Or any plugin that does this? Thx
TEST(something, thing, max_time: 3 seconds) {
ASSERT_EQ(expected_result, long_computation());
}
I'm not sure anything like this exists but I believe you can tailor some of the features you want at least partially.
You can measure the time of execution of your test yourself and add statements like ASSERT_GT(time_limit, measured_time).
Consider using https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#logging-additional-information for writing the timings or "long"/"fast" attributes.
Consider using https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#running-a-subset-of-the-tests for running only fast, or only long tests, f.e. run only fast tests (provided you named all long tests like *Long): ./foo_test --gtest_filter=-*Long

How to make cplex not output to terminal

I am using the IBM cplex optimizer to solve an optimization problem and I don't want all terminal prints that the optimizer does. Is there a member that turns this off in the IloCplex or IloModel class? These are the prints about cuts and iterations. Prints to the terminal are expensive and my problem will eventually be on the order of millions of variables and I don't want to waste time with these superfluous outputs. Thanks.
Using cplex/concert, you can completely turn off cplex's logging to the console with
cpx.setOut(env.getNullStream())
Where cpx is an IloCplex object. You can also use the setOut function to redirect logs to a file.
There are several cplex parameters to control what gets logged, for example MIPInterval will set the number of MIP nodes searched between lines. Turning MIPDisplay to 0 will turn off the display of cuts except when new solutions are found, while MIPDisplay of 5 will show detailed information about every lp-subproblem.
Logging-related parameters include MIPInterval MIPDisplay SimDisplay BarDisplay NetDisplay
You set parameters with the setParam function.
cpx.setParam(IloCplex::MIPInterval, 1000)

Debugging C++ in an Eclipse-based IDE - is there something like "step over loop/cycle"?

At the moment I'm using an eclipse-like IDE and the corresponding debug perspective, that most of you are probably familiar with. While debugging code I quite often find myself stepping through many lines of code and observing variables and double checking if everything is as it is supposed to be.
But suppose there is something like this:
1. important line, e.g. generating a new object;
2. another important line, e.g. some tricky class method;
3. for (int i = 0; i < some_limit; ++i)
4. some_array[i]++;
5. more important stuff;
Obviously I'm interested in what happens in lines 1,2 and 5 (I know this is a poor example, but please bear with me for a little while longer) but I don't want to step through all hundreds (or even thousands) of iterations of lines 3/4.
So, finally, my question: Is there some way to step directly over the for-cycle? What I do right now is set a new breakpoint at line 5 and let the program run as soon as I hit line 3 and I believe this is not an optimal solution.
edit: The eclipse implementation of what ks1322 proposed is called "Run to line" and is mapped to ctrl-r
Use until command instead of next.
From gdb documentation:
Continue running until a source line past the current line, in the
current stack frame, is reached. This command is used to avoid single
stepping through a loop more than once.
If you will use until instead of next, gdb will step over loops only once, which almost exactly what you want.