This question already has answers here:
"std::endl" vs "\n"
(10 answers)
Closed 1 year ago.
I am trying to understand buffer, endl vs \n and why the latter is more efficient than endl.
Specifically, I am reading this
https://www.geeksforgeeks.org/buffer-flush-means-c/
The following code is supposedly output 1,2,3,4,5 at once
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " ;
Sleep(300);
}
cout << endl;
return 0;
}
whereas the following will output each integer one at a time:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " << flush;
Sleep(300);
}
return 0;
}
However, both looks exactly the same during the time of execution, they appear one a time. Is my understanding wrong?
I'm also confused why endl is less efficient compared to \n.
From what I read, endl adds a \n and then flushes.
Isn't this more efficient, since it waits for the buffer to be full then output everything at once, compared to \n?
Please correct my flawed understanding, thank you.
You will clearly see the difference if you run the following code:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " " << flush;
usleep(300000);
}
cout<<"\n";
for (int i = 1; i <= 5; ++i)
{
cout << i << " " ;
usleep(300000);
}
cout << endl;
return 0;
}
std::endl is equivalent to using "\n" and flush together.
If your program is stable then simply use "\n" else go for std::endl. "\n" is more efficient in terms that it does not force the buffer to be flushed right then.
Also in your code, you might now be able to see the difference because you are using Sleep() which takes input in milisec, so try with greater value.
Related
im new to programming and was trying to understand buffers and came across :
https://www.tutorialspoint.com/what-does-buffer-flush-means-in-cplusplus#:~:text=The%20buffer%20flush%20is%20used,the%20buffer%20to%20be%20written.
it said that if the buffer is not flushed, the numbers will be printed at once while it will be printed one after the other while flushing the buffer.But after trying it on my computer, they both printed one after the other.
idk this might be a silly question
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
for (int x = 1; x <= 5; ++x) {
cout << x << " " << flush;
this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
}
cout << endl;
}
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
main() {
for (int x = 1; x <= 5; ++x) {
cout << x << " ";
this_thread::sleep_for(chrono::seconds(1)); //wait for 1 second
}
cout << endl;
}
On both windows and linux I am using Geany IDE and writing a c++ program. For some reason right now it is not catching an error on either linux/windows. I am using EXIT_SUCCESS and need to have the header file , right? also using copy function and it requires ? It only stops when I exclude and I discovered this because in my code I left it out by accident but it compiled, built and ran just fine.
It catches it when I use just G++, I'm not sure what is going on, could it be some setting I have in Geany?
Here is the code I'm working with
#include <iostream>
#include <algorithm>
#include <cassert>
//~ #include <cstdlib>
int main()
{
int xSize = 10;
int ySize = 50;
int xData[xSize];
int yData[ySize];
for(int i = 0; i < xSize; ++i) {
xData[i] = i;
std::cout << " First X Array value: "<< xData[i] << " " << std::endl;
}
std::cout << std::endl;
for(int i = ySize; i >= 0; --i) {
yData[i] = i;
std::cout << " First Y Array value: "<< yData[i] << " " << std::endl;
}
std::cout << std::endl;
std::copy(xData, xData+6,yData+42);
std::cout << "The copy function added it's first 6 values to the yData array starting at Y's 42nd array position" << std::endl;
for (int i = 42; i < ySize; ++i) {
std::cout << "First array value of Y is now: " << yData[i] << std::endl;
}
assert(yData[42]==0);
return EXIT_SUCCESS;
}
Thanks!
I have to write a program to test an integer value to determine if it is odd or even, and make sure my output is clear and complete. In other words, I have to write the output like "the value 4 is an even integer". I was also hinted that I have to check the value using the remainder modulo.
The issue I have is with the scanf() function. I get a syntax error:
'%=' expected a ')'
How do I fix this?
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
int scanf(%=2 , &number);
if (number == 0)
cout << "the value" << number << "is even";
else
cout << "the value" << number << "is odd";
return 0;
}
You are using scanf() incorrectly (read the scanf() documentation on cppreference.com). The first parameter expects a null-terminated string containing the format to scan, but you are not passing in anything that even resembles a string. What you are passing in is not valid string syntax, per the C++ language standard. That is why you are getting a syntax error.
You need to change this line:
int scanf(%=2 , &number);
To this instead:
scanf("%d", &number);
Though, in C++ you really should be using std::cin instead for input (you are already using std::cout for output):
std::cin >> number;
Try this:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number = 0;
cout << "enter an integer ";
if (cin >> number)
{
if ((number % 2) == 0)
cout << "the value " << number << " is even";
else
cout << "the value " << number << " is odd";
}
else
cout << "the value is invalid";
return 0;
}
I know this question is a little dated, however, if you are able to use modern C++ features. You can write a constexpr helper function such as this:
#include <cstdint>
constexpr bool isEven(uint32_t value) {
return ((value%2) == 0);
}
Then in your main function, you can traverse through a loop of N integers and output your display such as:
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isEven(i) ? "even" : "odd") << '\n';
}
return 0;
}
It's literally that simple. Here's another nice feature of using the constexpr helper function... You can also format your output as such:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isEven(i) << '\n';
}
return true;
}
If you are looking for something that is more efficient than using the modulo operator you can bitwise & with the least significant digit... The code above would then become:
#include <cstdint>
constexpr bool isOdd(uint32_t value) {
return (value&1);
}
And using it would be very similar as above, just make sure you reverse the wording in your output to match that from the function being used...
#include <iostream>
#include <iomanip>
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << " is "
<< (isOdd(i) ? "odd" : "even") << '\n';
}
return 0;
}
Again you can use the std::boolalpha manipulator to get this kind of output:
int main() {
for ( int i = 0; i < 100; i++ ) {
std::cout << std::setw(3) << std::setfill('0') << i << ": "
<< std::boolalpha << isOdd(i) << '\n';
}
return true;
}
I have an existing program that contains a loop over files. It does various things, providing lots of terminal output. I want to have an overall progress bar that remains stationary on the same line at the bottom of the terminal while all of the output from the file operations is printed above it. How should I try to do something like this?
EDIT: So, just to be clear, I'm trying to address the display problems inherent in something a bit like the following:
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int main(){
for (int i = 0; i <= 100; ++i){
std::cout << "processing file number " << i << "\n";
string progress = "[" + string(i, '*') + string(100-i, ' ') + "]";
cout << "\r" << progress << flush;
usleep(10000);
}
}
The only portable way of moving the cursor around that I know of is using \r to move to the beginning of the line. You mention that you would like to output stuff above the progress. Fortunately, you are in luck since you're on Linux and you can use the terminal escape codes to move around the terminal freely. Look at this example:
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << endl;
for (int i=0; i <= 100; ++i)
{
string progress = "[" + string(i, '*') + string(100-i, ' ') + "]";
cout << "\r\033[F" << i << "\n" << progress << flush;
usleep(10000);
}
}
Here, I added the ability to print the progress value above the progress bar by moving to the beginning of the line using \r and one line up using escape code \033[F before printing. Then, printed one line, moved down one line with \n
and re-printed the progress.
You can go even further and move your cursor to any X,Y position in the terminal before printing. For that use the escape code \033[Y;Xf before your output.
For a good list of escape codes, check out Wikipedia: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
So, it is possible to achive that behavior without using additional libs like ncurses, but maybe it is actually what you want if you intend to create a more gui-like experience.
Fixing your attempt:
void print_progress_bar(int percentage){
string progress = "[" + string(percentage, '*') + string(100 - percentage, ' ') + "]";
cout << progress << "\r\033[F\033[F\033[F" << flush;
}
int main(){
cout << endl;
for (int i=0; i <= 100; ++i){
std::cout << "processing file number " << i << "\n";
std::cout << " doing thing to file number " << i << "\n";
std::cout << " doing another thing to file number " << i << "\n";
print_progress_bar(i);
usleep(10000);
}
cout << endl;
cout << endl;
cout << endl;
cout << endl;
}
I wrote this, but when running it, the console just sits at "Running..." and won't really do anything, at least that I can see. I am kind of at a loss here as I can't think of anything else to do.
#include <iostream>
#include <cmath>
#include <cstdlib>
int main(void) {
int count = 0;
do {
int a = 1;
int b = 2;
int c = 3;
int total;
for (a=1;a<b;a++) {
for (b=2;b<c;b++) {
for (c=3;c<=1000;c++) {
total = a+b+c;
if (total == 1000 && a*a + b*b == c*c) {
std::cout << a << ", " << b << ", " << c;
}
}
}
}
count++;
} while(count < 1000);
return 0;
std::cin.get();
}
You might not see any output because your terminal is line-buffered and you never write a line break or flush the stream. To fix this you could add std::endl to your output line:
std::cout << a << ", " << b << ", " << c << std::endl;
This way you should see all triples as soon as they are found, but the program will still take a long time to complete. It might even take a long time till any results are found. You could speed the program up by avoiding some of the nested loops.