Controlling output of program - c++

I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control
I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want it to repeat the output in 1 second rather than 1.0005 seconds).
I also am wondering if there's a way to just have it output (say 1) and then have it wait for me to press enter, which will make it output the second part (2).
Also, I'd appreciate any other suggestions on how to control output.

If you're on Windows, a quick way to pause is to call system("pause"); This isn't a very professional way of doing things, however.
A way to pause with the std namespace would be something like this:
cout << "Press Enter to continue . . ." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
As for your main question... If you're just dealing with text output to the user, it's not possible for them to notice a five microsecond delay. They can notice if your interval lengths fluctuate by tens of milliseconds, however. This is why sleep(..) functions sometimes fail.
Let's take your example of wanting to output another number in the Fibonacci sequence once per second. This will work just fine:
#include <ctime>
#include <limits>
#include <iostream>
void pause() {
std::cout << "Press Enter to continue . . ." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int main() {
clock_t next = clock();
int prev1, prev2, cur = 0;
for (int i = 0; i < 47; ++i) {
if (i < 2) cur = i;
else cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
while (next > clock());
std::cout << (i+1) << ": " << cur << std::endl;
next += CLOCKS_PER_SEC;
}
pause();
return 0;
}
The next number in the sequence is computed and ready to print prior to the wait, thus the computation time will not add any delay to the timed output.
If you want your program to continue outputting at a fixed rate while your program works in the background, you'll need to look into threads. You can have your results added to a queue in one thread, while another thread checks for results to print once per second.

Related

c++ stdout flushes stream unexpectedly

#include <iostream>
#include <thread>
using namespace std;
int main()
{
for (int i = 0; i < 10000; i++) {
cout << "Hello\n";
}
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
In my code, I didn't call any std::flush or std::endl, but the hello's are printed before the 2 seconds delay. I am expecting to print all the hello's after the 2 seconds delay, but it didn't. My code runs like this:
Hello
Hello
.
.
.
Hello
Hello
(after 2 seconds)
2 seconds have passed
[terminated]
Why is this happening?
First of all, you're writing more output than a typical file buffer will hold, so you'd almost always expect at least some of the output to show up before the sleep.
Second, you're doing a lot of separate output calls, so if cout is unit-buffered, each one is going to be flushed immediately.
Third, you're writing a new-line at the end of each item, so if cout is line-buffered, (yup) each one is going to be flushed immediately.
So, if you want a better chance of seeing at least some of the output showing up after the sleep ends, turn off unit buffering and get rid of the new-lines:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout << nounitbuf;
for (int i = 0; i < 1000; i++) {
cout << "Hello";
}
// display something different to make it easier for user to see
// whether all output showed up before sleep or not.
cout << "...";
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
But even with this, there's no guarantee the behavior will change. Rather the contrary, most implementations go to some pain to assure that output written to the console shows up as promptly as possible, so even when you take steps toward delaying it, it'll still probably show up before the sleep. But this might improve your chances a little bit anyway.

Design of a simple progress bar to cout goes from 0->100% instantly at the end in C++

I would like to make a very basic progress indicator by printing an 'X' char to cout every time a loop progresses another 10%. I am trying to do this as shown in the code pasted below, but it doesn't seem to be working - when really it seems it should.
It's supposed to display steady progress throughout the loop, but instead I get all the X's coming at once after the loop has finished. This is not because the loops are completed too quickly for me to perceive. To verify this you can add an extra 'F' to "TOTAL" to increase the duration of the looping substantially, and you'll see it's not just a question of perception.
Any ideas what might be causing this?
#include <iostream>
#define TOTAL 0xFFFFFFF
using namespace std;
int main(void) {
//Make a counter for counting loops
double counter = 0;
// Set it to trigger after each 10% of progress
double counterMax = TOTAL / 10;
cout << "Starting now..." << endl;
for (double i = 0; i < TOTAL; i++) {
// Do something... anything
i++;
i--;
// Increment the counter
counter++;
// Print an X when the counter exceeds the 10%
// trigger point, and then reset the counter.
if (counter > counterMax) {
cout << 'X';
counter = 0;
}
}
cout << endl << "Done!";
return 0;
}
System input/output calls are usually slow operations. To increase the efficiency of programs, input and output streams are often buffered, to reduce the number of calls to the operating system.
When a program needs "non-buffered" output, one solution is to use the buffered output functions, and simple "flush" the output to ensure the operating system processes any output which has been queued in any buffers.
When the output buffer is filled, or when the stream is closed, it is automatically flushed. The standard output is also automatically flushed by certain sequences, like endl. But you can trigger a flush of the standard output at any point by called cout.flush() or by using the flush manipulator, like:
cout << 'X' << flush;

Simple program, cannot get for loop to execute

Brand new programmer, so green behind the ears that I could be a frog. The intent of this program is to use a for loop (not a simple formula) to add all integers up to a user designated value. It executes all code up to the for loop perfectly, however the for loop does not seem to run. Here is the code in question:
#include "stdafx.h"
#include <iostream>
int main(int num=0)
{
int sum = 0;
std::cout << "This program will sum all integers up to a given value";
std::cout << std::endl << std::endl;
std::cout << "Please enter a number "<<std::endl;
std::cin >> num;
std::cout << std::endl << "You've chosen the number " << num<<std::endl;
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
std::cout << "The sum of all numbers up to " << num << " is " << sum;
}
Any help is appreciated!
When it meets return for the first time, the program will be end.
Please put the return at the end of main function.
One more thing, shouldn't use parameter num in main function.
Write a separately function sum_all_integers and then call it in main function.
Good news: your code works! The issue is that when return (sum); is called, the function is exited, and the line that would print out your answer is not executed.
I would also recommend adding the using namespace std; line after your includes, so that you don't end up with so much std:: pollution. Also main should not take any arguments, so put that int num=0 line inside the main block.
Oh, you should also be aware of your return line indentation.
In this section
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
Your program will exit.
This boils down to what other answers have mentioned: return from main means exiting the program. Keep in mind that is is true even from within a loop like while or for - doing so is how one might design a search function which exits as soon as it has a result, for example.
To exit a for loop prematurely, use break. To continue to the next iteration and skip further code in the loop, use continue.
Also note that the indentation of return is misleading - it will be executed after the for loop, since the lack of brackets ({}) will make for only loop through the next line, which is sum += i; Keep in mind that C++ is not a whitespace sensitive language, so indentation means nothing to the logic (I like to abuse this in large blocks of similar code by tab-aligning). This is also a good example of why it is common practice to use brackets even when not strictly necessary. EDIT See also Apple's infamous "goto fail" bug.
You return the sum right after the loop:
for (int i = 1; i <= num; ++i)
sum += i;
return (sum);
This means, you sum up the numbers and then exit the program before you print the result.

How to "Bind" a number to a string of words/phrase so that I can call it up in a loop?

I'm working on a project where I need to have the computer print the 12 days of Christmas lyrics. I thought of an idea where I make a FOR loop and have it repeat 12 times. Every time the day changes with the unary operator "++" Here's what I mean:
int main()
{
string Print = first = 1; //Here I want first to become a number so that I can call it up in FOR loop.
cout << "On the first day of Christmas, \nmy true love sent to me\nA partridge in a pear tree.\n" << endl;
for(int loop = 0; loop <= 12; loop++)//This part is a simple for loop, it starts at 0 and goes to 12 until it stops.
{
cout << "On the " << (1,2,3,4,5,6,7,8,9...12) << " day of Christmas,\nmy true love sent to me\n" << endl; HERE!!!!
Here is where I'm having issue. I want the numbers to call in strings to say the day. As in x = 1 will call in "First" and then I can move the number up by using "x++" which will result in x = 2 and then it will say "Second".. all the way to 12. Anyone know how I can resolve this issue?
}
This involves a simple but important part of programming called an array. I don't want to give you the answer directly - you need to use these (or similar structures) all the time, and it is very important to practice their use and understand them. Let's make a simple program using arrays that prints "Hello World":
#include <iostream>
#include <string>
int main() {
std::string words[2]; //make an array to hold our words
words[0] = "Hello"; //set the first word (at index 0)
words[1] = "World"; //set the second word (at index 1)
int numWords = 2; //make sure we know the number of words!
//print each word on a new line using a loop
for(int i = 0; i < numWords; ++i)
{
std::cout << words[i] << '\n';
}
return 0;
}
You should be able to figure out how to use a similar tactic to get the functionality you asked for above. Working Ideone here.

C++ Timer implementation

I'm trying to implement a "timer" function in C++ for the program to do something after some seconds.
However, I've got unexpected results.
short e, sum;
clock_t start;
double duration=0;
for (e=0; e<4; e++) {
start = clock();
while (duration < 1) {
duration = (clock() - start)/(double)CLOCKS_PER_SEC;
}
cout << duration;
duration = 0;
sum += e;
/* Calculate EPOCH error */
cout << e;
}
cout << "\n" << e<< "\n";
The results I expect are:
console output every second, followed by e (0,1,2,3)
at the end of the execution I expect sum to be 0+1+2+3 = 6,
Results obtained:
console output followed by e, all together when execution finishes
sum = 6
What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,
Your problem is that the output stream isn't flushed during your loop. Actually writing pieces of text to the console is somewhat expensive. Therefore the input is buffered and only written to the console when a flush occurs. Flushing the stream can be accomplished by streaming std::flush:
cout << e<<std::flush;
std::endl will also flush the stream in addition to adding a newline (writing \n might also do it, but that's not guaranteed).
As a sidenote: you might want to consider adding some sort of seperators between your numbers to make the output readable.