I don't know if it's related to flush in ostream. Since, endl is end with flush right? I don't know what is flush and how it works.
I have a function that will print out each characters of string every second. I want to print it out whitout new line after every characters. Then, I write this function:
using namespace std;
void print_char_per_second (string text) {
int i = 0;
int len = static_cast<int>(text.length());
while (i < len) {
int tick = clock() % CLOCKS_PER_SEC;
if (tick == 0) {
cout << text[i];
i++;
}
}
}
It prints the text one after while loop finished looping and prints all of characters in the text at once. Why this is happen?
Flushing makes sure all output written to the stream so far is shown on the console.
You can do std::cout << std::flush or std::cout.flush() after each output operation to make sure the output is shown on the console immediately.
Right now it's just writing everything to the stream and only flushing the stream after the loop.
Related
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;
I have an array that contains chars.
I am trying to print out an element once every second.
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
sleep(1);
i++;
}
This for some reason just waits for 110 seconds and than prints out the whole array at once.
But if i add a new line after every element it works just fine
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
cout<< endl;
sleep(1);
i++;
}
Any recommendation on how to get each element to print chronologically without having to make a newline?
This for some reason just waits for 110 seconds and than prints out the whole array at once.
Actually it doesn't, but your output is buffered. There is buffering in the C++ stream object, in the OS data pipe, and in your terminal.
Your stream thinks it would be a waste of resources passing characters through one at a time, and it's kind of right: the stream doesn't know you have a second to wait in between each one.
You don't need the newline, though; you can basically force a flush like so:
std::cout << std::flush;
Recall that std::cout << std::endl is equivalent to std::cout << '\n' << std::flush, and it's the '\n' part that you don't want.
This is usually enough but you may also need to reconfigure your terminal to turn off line buffering. (That's unlikely for output but quite common for input).
I have a function print_string which takes in a character array as its argument.
For some reason I can't get it to print out if I use a while loop like
int i = 0;
while(str[i]!= '\0'){
cout << str[i];
i++;
}
but if I use a for loop and specify the length of the array it can.
Thanks
The code works for me. My guess: you're probably experience the problem with buffering. std::cout is buffered, so characters first go into buffer, and then, at certain points, the contents of the buffer are put on screen.
The most typical way to force this is: std::cout << std::endl;
Also, tip: std::cerr is unbuffered, so you could use it for debugging this issue.
I am writing a program that allows the user to enter a sentence which then gets stored in a string and then the program will remove any full stops in the sentence and then create a list of each individual word in the string before outputting that list to the console.
the program is working perfectly as long as there is only 1 full stop in the sentence but if there are any more than that it throws this exception:
Unhandled exception at at 0x7696B727 in Project6.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0022F8B8.
and then if I continue to run it it throws:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
any suggestions? (and before anyone asks, i know you usually only have 1 full stop in a sentence but i need to do it with more than 1 as part of testing.
here is the code:
#include <iostream>
#include <string>
using namespace std
string sSentence; // sets up a string variable called sSentence
int i = 0;
void RemoveFullStop()
{
while(sSentence.find (".") != string::npos) // the program runs this loop until it cannot find any more full stops in the string
{
i = sSentence.find("." , i); // find the next full stop in the string and get the character count of the space and place it in the variable i
sSentence.replace(i,1,""); // remove the full stop
}
}
void ListWords()
{
while(sSentence.find (" ") != string::npos) // the program runs this loop until it cannot find any more spaces in the string
{
i = sSentence.find(" " , i); // find the next space in the string and get the character count of the space and place it in the variable i
// cout << i << endl; // output the contents of iWordSpace to the console (used for debugging - no longer used)
sSentence.replace(i,1,"\n");
// cout << sSentence << endl; // output the contents of iWordSpace to the console (used for debugging - no longer used)
}
}
int main()
{
getline(cin, sSentence); // get user input and store it in sSentence (using the getline function so the .find operation works correctly)
RemoveFullStop(); // calls the RemoveFullStop void function that removes all full stops from the string
ListWords(); // calls the ListWords void function that splits the string into a list of words
cout << endl; // formatting line
cout << "The words that were in the sentence were:" << endl;
cout << endl; // formatting line
cout << sSentence << endl;
cout << endl; // formatting line
system("pause");
return 0;
}
The problem is that you keep re-using i, in both RemoveFullStop and ListWords.
i only ever increases, and so eventually it can get past the end of the string.
You really shouldn't need a global i variable at all, to do this task.
The reason this happens is that when sSentence.find(" " , i) in ListWords runs, i's value is not 0 because it was already defined in RemoveFullStop(). To fix this, first remove int i = 0;, then add it to RemoveFullStop() and ListWords()
Also, while this is just a style thing and won't effect your codes ability to run, I wouldn't call this variable i as i,j,k usually imply counters. Call this variable something more appropriately descriptive.
Here is the relevant code as it should be.
using namespace std
string sSentence;
void RemoveFullStop()
{
int charPlace = 0;
while(sSentence.find (".") != string::npos)
{
charPlace = sSentence.find("." , charPlace);
sSentence.replace(charPlace,1,"");
}
}
void ListWords()
{
int charPlace = 0;
while(sSentence.find (" ") != string::npos)
{
charPlace = sSentence.find(" " , charPlace);
sSentence.replace(charPlace,1,"\n");
}
}
My code look like below
int i=0;
while(i<10){
cout<<"Hello";
sleep(1);
i++
}
In Windows the code prints on each loop but in Linux it prints everything after exiting while loop . And also if I put an endl at the last of cout then it prints on each loop. Why this happening ?. Can anyone explain this behavior?.
Try to use cout.flush(); maybe the two OS has different policy in term of buffering the stdout.
For efficiency reasons, sometimes the standard streams will be implemented with a buffer. Making lots of tiny writes can be slow, so it will store up your writes until it gets a certain amount of data before writing it all out at once.
Endl forces it to write out the current buffer, so you'll see the output immediately.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i < 10){
cout << "Hello" << endl;
sleep(1);
++i;
}
}