Namespaced Functions interfering with print - c++

I'm new to the site and browsed several similar sounding questions but haven't found my exact problem. I suspect I'm making elementary mistakes. A link to an answer would be appreciated, or an explanation, and again I'm sorry if my question doesn't even match the title of the post.
For c++ on the Cxxdroid app for android and in Visual Studio C++:
I'm trying to experiment with classes and namespaces to provide flexible utility to the class. I want to use different implementations of the same function for personal analysis of certain algorithms on data structures; namely arrays vs lists/trees and also between recursive and iterative implementations of standard procedures. I know how to do asymptotic analysis but my stubborn mind wants real numbers.
Unfortunately, however, I can't even seem to get namespace functions to work without blowing up normal functionality. Please note, I haven't learned c++ formally yet because I'm exploring ahead of my introductory c/c++ course.
For example:
#include <iostream>
namespace iterative{
int power(int base,int expo){...}
}
namespace recursive{
int power(int base,int expo){...}
}
int main(int argc,char* argv[]){
int result = 0;
int num = 3;
int exp = 2;
//Expecting 9 in result
std::cout << "This prints fine" << std::endl;
result = iterative::power(num,exp);
std::cout << result;
std::cout << " This number and text doesn't print" << std::endl;
return 1;
}
I had a much more complex function with classes above the namespaced functions (search function for node classes inside a list/tree class) but it never worked. Then I just threw together the above snippet and tried to print result but the std::cout never fired after my function call.
Can anyone offer insight into what I'm doing wrong here? The first cout prints and the second wont. Further, execution hangs during the function call; the solution keeps running until I force it to stop.
I've tried to comment out one of the namespaces while using the other.
I've tried the using keyword with the namespace_name.
I've tried passing integers without variable usage: result = power(3,2);
I've tried printing the function result directly: std::cout << power(3,2) << std::endl;
I can't seem to get it to work on either application. I know this seems like a silly and simple question but after about a week of browsing the internet I'm inundated with very vague answers to questions regarding syntax. Perhaps I'm just not connecting the dots to my own problem...
Is my syntax in definition wrong?
Is my syntax in calling the function wrong?
Is my syntax in variable assignment wrong?
I'm at my wits' end.
Edit:
Now I feel really stupid.
You were correct. I didn't increment my variable in the iterative implementation, which meant it hung up on an infinite loop. I had to print the loop to see the numbers spitting out like I'm Neo in The Matrix. Unfortunately, I didn't test the recursive function because it felt dangerous to do so if I couldn't even get the iterative function to call first...
I was so focused on using namespaces for the first time that I never looked at the loop properly.
Thank you, and sorry for the bother. I'm going to try to extend this experiment to namespace-defining class member functions now.
Edit2: Feel free to delete this...unless it's felt that my stupidity can help others.

Silly mistake was made:
...
int power(int base,int expo){
int i = 0;
int retval = 1;
while( i < expo ){
retval *= base;
//Never did i++; or i = i + 1;
//Had to std::cout << retval; in loop to catch it
}
return retval;
}
...

Related

Find the Narcissistic value among below numbers

#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int Narsic(stack<int> stk)
{
int x=0;
int temp=0;
int val=0;
int power_count = stk.size();
while(! stk.empty())
{
x = stk.top();
stk.pop();
temp = pow(x,power_count);
val = val + temp;
}
cout<<val;
}
int main()
{
int num,indic;
num = 1652;
stack<int> numstack;
while(num>0)
{
indic = num%10;
num = num/10;
numstack.push(indic);
}
Narsic(numstack);
return 0;
}
Basically this program is to find the Narcissistic value of a given integer, my codes can be successfully executed and it is correct, but somehow, i think , maybe it is a bit lengthy, so the purpose of posting this problem is, whether anyone can give me suggestions on how to improve the codes above?
Sorry , I'm a beginner and just started learning C++. I hope this community won't get furious against by sucky codes XD.
(Oh yeah, i do search for some codes online and implement them partially here, so if anyone saw similar codes, please be aware that i have made changes, sorry if this irritates you.)
It looks like you're largely asking about style. I'm going to take your code and edit it to be more in keeping with what I would do, then I'll comment below.
#include <iostream>
#include <stack>
#include <cmath>
using std::cout;
using std::endl;
using std::stack;
/**
* Return the Narcissistic value of the digits stored in the stack.
* A Narcissistic value is (insert description).
*/
int narsic(stack<int> stk)
{
int result = 0;
int power_count = stk.size();
while (! stk.empty() ) {
int digit = stk.top();
stk.pop();
result += pow(digit, power_count);
}
return result;
}
/**
* Entry point.
*/
int main() {
int num;
num = 1652;
stack<int> numstack;
while (num>0)
{
int indic = num % 10;
num /= 10;
numstack.push(indic);
}
int result = narsic(numstack);
cout << "Result: " << result << endl;
return 0;
}
I use Java's naming conventions. Class names begin with an upper case letter. Variables and methods begin with lower case letters. This isn't necessarily the C++ way of doing it, but I programmed Java a long time, and it's what I prefer. You'll want to find a style for your academic work, and then use whatever your future employer uses.
I prefer more whitespace to make code readable -- especially for myself. I'm nearly 60 years old, with old eyes, and as code runs all together, it gets harder and harder to read. I've added whitespace here and there.
A blanket using namespace std is considered dangerous, but I don't like sticking std:: all over the place, so I tend to add specific using statements, although not too many.
You were missing a return statement in narsic().
And you had an unusual indentation style. Old-school C/C++ is either 4 spaces or use a tab, but set your editor to 4-space tabs. You indented the braces and then indented again. That would be odd. Some people put the open brace on the same line (I moved them) and some on the next line the way you did. I actually will put them on the next line if it makes the code more readable -- like if there's an obnoxiously long and complicated if-clause.
I moved variable declaration to just as the variables were about to used. This is better for a variety of reasons, including one less initialization plus makes your code smaller. Plus, it keeps scoping rules much tighter.
I switched a num = num / 10 to num /= 10. Similar thing with result +=.
I don't like the variable name val. I changed to result. I think I might have made one or two other variables more descriptive, too.
I added function comments and I did it in the doxygen style. Commenting each method means tools can auto-generate documentation. It also helps break code up a little bit better visually. For comments, it's important to provide information not in the code. The comment for main is trivial, but having it still helps if you actually use a documentation generator -and- provides a visual break.
A change I did NOT make but would normally do: I prefer main to be the first method in my files (at the top), so I would have made a forward reference to narsic() and moved it below main. I didn't do that just because I wanted to keep the code in the same order you had it.
I moved the cout statement and included an endl.

How to print the name of a variable with parameters?

I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
Let me explain a simpler case with a toy solution based on a macro:
int i = 1771;
I can print the variable_name with
#define toy_solution(x) cout << #x ;
If I execute
toy_solution(i);
"i" will be printed.
Now, imagine there is a well-allocated table T.
I would like to write in the program:
solution(T[i]);
and to read on the screen "T[1771]".
An ideal solution would treat the two cases, that is :
ideal_solution(i) would print i.
ideal_solution(T[i]) would print T[1771].
It is not important to me to use a macro or a function.
Thanks for your help.
#define toy_solution(x, i) cout << #x << "[" << i << "]"
I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
well, as you did not understand my comment, I'll say out loud in an answer:
what you want to do is not possible
You have to choose between either #Alin's solution or #lizusek.
I think that #lizusek's solution is better because you're writing C++ code, so if you can do something that gives the same result than with using macros, you should use plain C++ code.
edit: let my try to explain why this is not possible
so what you want is:
f(T[i]) -> T, i
The only way you could write that so it would make sense in preprocessor is:
#define f(T[i]) cout<<#T#<<#i#
but then the preprocessor will give an error, because you can't index an array as a function (even a macro function) parameter:
test.c:5:12: error: expected comma in macro parameter list
#define f(T[i]) cout<<#T#<<#i#
^
If you try to do the same thing using a C++ function, then it's even more non-sense, as a function call such as:
toy_solution(t[i]);
would actually be translated to the value t[i] points to at runtime, so inside the function you'll never be able to known that the given value was actually in an array. So what you want is wrong, and you should stick to good coding practices: using a function and if what you want is:
toy_solution(t[i]);
then use:
toy_solution("t", i);
Possible solutions that you should never use
well, when I say it's not possible, it's that the only solutions I can think off are so twisted that you'd be insane to actually use them in your code… And if you do, I hope I'll never read one of your code or I may become violent :-) That's why I won't show you how or give you any code that could help do what I'm about to tell you.
use a template system
You could either write your code using your own template system or use one commonly used for HTML processing to process your source code through it and apply a transformation rule such as:
toy_solution(t[i]) -> toy_solution("t", t[i])
it's definitely possible, but it makes your build chain even more complicated and dependant on more tools. C/C++ build toolchain are complicated enough, please don't make it worst.
Or you code make your own fork of C and of a C compiler to change the syntax rules so what you want becomes possible. Though, I personnally would never use your fork, and then I'd go trolling and flaming about this on HN, deeply regretting to have given you such a bad idea :-)
use a custom class to encapsulate your arrays in
if you do something like:
template<T>
class Element {
T value;
List<T> _owner;
[…]
}
template<T>
class List {
Element<T> values[];
std::string _name;
[…]
}
so that when you call the function
toy_solution(T[i]);
the implementation would look like:
void toy_solution(Element<T> e) {
std::cout<<e.get_list_name()<<" "<<e.get_value()<<std::endl;
}
but that's sooo much boilerplate and overhead just to avoid doing a simple function definition that does not look as nice as you dream of, that I find it really stupid to do so.
You can write a function as simple as that:
void solution( std::string const& t, int i) {
std::cout << t << "[" << i << "]";
}
usage:
int i = 1771;
solution( "T", i);
You can also write a macro, but be aware that this is not type safe. Function should be preferred.

Is this function well declared?

this is my first question. I'm really new to programming and I'm struggling when it comes to discerning from well structured code from WTF codemonkey code. Is there anything I should have done different when creating this ubber simple program? My main concern is regarding the function.
#include <iostream>
using namespace std;
void enter_numbers ( int & iNum1, int & iNum2 ) {
cout << "Enter first number" << endl;
cin >> iNum1;
cout << "Enter second number" << endl;
cin >> iNum2;
}
float calc_avg ( int iNum1, int iNum2){
float fRes;
fRes =(float)(iNum1 + iNum2)/2;
return fRes;
}
void show_avg ( float fRes ) {
cout << "Average is: " << fRes;
}
void main () {
int iNum1;
int iNum2;
enter_numbers ( iNum1, iNum2);
float fRes = calc_avg (iNum1, iNum2);
show_avg ( fRes );
fflush(stdin);
getchar ();
}
You should not fflush an input stream, as described here: http://www.gidnetwork.com/b-57.html
Your main function should have int as return type and return 0, for successful execution:
What should main() return in C and C++?
In rest, your code seems fine. Note that for a beginner you should be happy, it is pretty good as it is. I just mentioned a few improvements you may want to made and pointed some sources for further documentation, as i guess you want to learn more.
Every corporate culture - or any other group of people working on code together - is going to have a set of coding style guidelines, variable and function naming conventions, and so on and so forth. There are going to be a vast plethora of opinions you'll hear (probably really soon =D) about how to make code readable, and the following issues are mostly religious:
Hungarian notation (variable names like lpctszName) vs plain English. My opinion is that there's a time and a place for it. Look up "Apps Hungarian" vs "Systems Hungarian".
Indentation. We all agree (pretty much - dissenters?) that the bodies of a compound statement (e.g. function definitions) should be indented. So do that. However, there are really heated debates about which line the brace goes on. I like the opening brace at the end of the line. Look up "One true indent style".
ReadableVariable vs readableVariable vs readable_variable and so on.
The bottom line is that, like any other body of text, code has an audience. It's the people you're working with, or who take over maintenance of your code, or who test it. In personal projects, it's you, some weeks down the road when you don't remember what variables were what. Your coding style should be consistent with what that audience knows.
Other than that, if there are no exceptions or compile-time errors, your code is good. In the future, working code goes on the code review StackExchange, though, and conceptual questions go to the programmers StackExchange. Welcome to StackOverflow =D.
Just write num1, num2, res and not iNum1, iNum2, fRes.
The type is already visible as part of the declaration.

Infix equation solver c++ while loop stack

Im creating an infix problem solver and it crashes in the final while loop to finish the last part a of the equations.
I call a final while loop in main to solve whats left on the stack and it hangs there and if i pop the last element from the stack it will leave the loop and return the wrong answer.
//
//
//
//
//
#include <iostream>
#include<stack>
#include<string>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
using namespace std;
#define size 30
int count=0;
int count2=0;
int total=0;
stack< string > prob;
char equ[size];
char temp[10];
string oper;
string k;
char t[10];
int j=0;
char y;
int solve(int f,int s, char o)
{
cout<<"f="<<f<<endl;
cout<<"s="<<s<<endl;
cout<<"o="<<o<<endl;
int a;
if (o== '*')//checks the operand stack for operator
{
cout << f << "*" << s << endl;
a= f*s;
}
if (o == '/')//checks the operand stack for operator
{
cout << f << "/" << s << endl;
if(s==0)
{
cout<<"Cant divide by 0"<<endl;
}
else
a= f/s;
}
if (o == '+')//checks the operand stack for operator
{
cout << f << "+" << s << endl;
a= f+s;
}
if (o == '-')//checks the operand stack for operator
{
cout << f << "-" << s << endl;
a= f-s;
}
return a;
}
int covnum()
{
int l,c;
k=prob.top();
for(int i=0;k[i]!='\n';i++)t[i]=k[i];
return l=atoi(t);
}
char covchar()
{
k=prob.top();
for(int i=0;k[i]!='\n';i++)t[i]=k[i];
return t[0];
}
void tostring(int a)
{
stringstream out;
out << a;
oper = out.str();
}
void charstack(char op)
{
oper=op;
prob.push(oper);
}
void numstack(char n[])
{
oper=n;
prob.push(oper);
}
void setprob()
{
int f,s;
char o;
char t;
int a;
int i;
t=covchar();
if(ispunct(t))
{
if(t=='(')
{
prob.pop();
}
if(t==')')
{
prob.pop();
}
else if(t=='+'||'-')
{
y=t;
prob.pop();
}
else if(t=='/'||'*')
{
y=t;
prob.pop();
}
}
cout<<"y="<<y<<endl;
i=covnum();
cout<<"i="<<i<<endl;
s=i;
prob.pop();
t=covchar();
cout<<"t="<<t<<endl;
if(ispunct(t))
{
o=t;
prob.pop();
}
i=covnum();
cout<<"i="<<i<<endl;
f=i;
prob.pop();
t=covchar();
if (t=='('||')')
{
prob.pop();
}
a=solve(f,s, o);
tostring(a);
prob.push(oper);
cout<<"A="<<prob.top()<<endl;
}
void postfix()
{
int a=0;
char k;
for(int i=0;equ[i]!='\0';i++)
{
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
if(ispunct(equ[i]))//checks array for operator
{
if(count>0)//if the int input is done convert it to a string and push to stack
{
numstack(temp);
count=0;//resets the counter
}
if(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
setprob();
i++;//pushes i to the next thing in the array
total++;
}
while(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
i++;
}
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
if(ispunct(equ[i]))
{
if(equ[i]==')')//if char equals the ')' then set up and solve that bracket
{
i++;
}
charstack(equ[i]);
}
if(isdigit(equ[i]))//checks array for number
{
temp[count]=equ[i];
count++;
}
}
}
}
int main()
{
int a=0;
char o;
int c=0;
cout<<"Enter Equation: ";
cin>>equ;
postfix();
while(!prob.empty())
{
setprob();
a=covnum();
cout<<a<<" <=="<<endl;
prob.pop();
cout<<prob.top()<<"<top before c"<<endl;
c=covnum();
a=solve(c,a,y);
}
cout<<"Final Awnser"<<a<<endl;
system ("PAUSE");
return 0;
}
Hope this isn't too harsh but it appears like the code is riddled with various problems. I'm not going to attempt to address all of them but, for starters, your immediate crashes deal with accessing aggregates out of bounds.
Example:
for(int i=0;k[i]!='\n';i++)
k is an instance of std::string. std::string isn't null-terminated. It keeps track of the string's length, so you should be do something like this instead:
for(int i=0;i<k.size();i++)
Those are the more simple kind of errors, but I also see some errors in the overall logic. For example, your tokenizer (postfix function) does not handle the case where the last part of the expression is an operand. I'm not sure if that's an allowed condition, but it's something an infix solver should handle (and I recommend renaming this function to something like tokenize as it's really confusing to have a function called 'postfix' for an infix solver).
Most of all, my advice to you is to make some general changes to your approach.
Learn the debugger. Can't stress this enough. You should be testing your code as you're writing it and using the debugger to trace through it and make sure that state variables are correctly set.
Don't use any global variables to solve this problem. It might be tempting to avoid passing things around everywhere, but you're going to make it harder to do #1 and you're also limiting the generality of your solution. That small time you saved by not passing variables is easily going to cost you much more time if you get things wrong. You can also look into making a class which stores some of these things as member variables which you can avoid passing in the class methods, but especially for temporary states like 'equ' which you don't even need after you tokenize it, just pass it into the necessary tokenize function and do away with it.
initialize your variables as soon as you can (ideally when they are first defined). I see a lot of obsolete C-style practices where you're declaring all your variables at the top of a scope. Try to limit the scope in which you use variables, and that'll make your code safer and easier to get correct. It ties in with avoiding globals (#2).
Prefer alternatives to macros when you can, and when you can't, use BIG_UGLY_NAMES for them to distinguish them from everything else. Using #define to create a preprocessor definition for 'size' actually prevents the code above using the string's 'size' method from working. That can and should be a simple integral constant or, better yet, you can simply use std::string for 'equ' (aside from making it not a file scope global).
Prefer standard C++ library headers when you can. <ctype.h> should be <cctype>, <stdlib.h> should be <cstdlib>, and <stdio.h> should be <stdio>. Mixing non-standard headers with .h extension and standard headers in the same compilation unit can cause problems in some compilers and you'll also miss out on some important things like namespace scoping and function overloading.
Finally, take your time with the solution and put some care and love into it. I realize that it's homework and you're under a deadline, but you'll be facing even tougher deadlines in the real world where this kind of coding just won't be acceptable. Name your identifiers properly, format your code legibly, document what your functions do (not just how each line of code works which is something you actually shouldn't be doing so much later as you understand the language better). Some coding TLC will take you a long way. Really think about how to design solutions to a problem (if we're taking a procedural approach, decompose the problem into procedures as general units of work and not a mere chopped up version of your overall logic). #2 will help with this.
** Example: rather than a function named 'postfix' which works with some global input string and manipulates some global stack and partially evaluates the expression, make it accept an input string and return* the individual tokens. Now it's a general function you can reuse anywhere and you also reduced it to a much easier problem to solve and test. Document it and name it that way as well, focusing on the usage and what it accepts and returns. For instance:
// Tokenize an input string. Returns the individual tokens as
// a collection of strings.
std::vector<std::string> tokenize(const std::string& input);
This is purely an example and it may or may not be the best one for this particular problem, but if you take a proper approach to designing procedures, the end result is that you should have built yourself a library of well-tested, reusable code that you can use again and again to make all your future projects that much easier. You'll also make it easier to decompose complex problems into a number of simpler problems to solve which will make everything easier and the whole coding and testing process much smoother.
I see a number of things which all likely contribute to the issue of it not working:
There are no error or bounds checking. I realize that this is homework and as such may have specific requirements/specifications which eliminate the need for some checks, but you still need some to ensure you are correctly parsing the input. What if you exceed the array size of equ/tmp/t? What if your stack is empty when you try to pop/top it?
There are a few if statements that look like else if (t == '+' || '-') which most likely doesn't do what you want them to. This expression is actually always true since '-' is non-zero and is converted to a true value. You probably want else if (t == '+' || t == '-').
As far as I can tell you seem to skip parsing or adding '(' to the stack which should make it impossible for you to actually evaluate the expression properly.
You have a while loop in the middle of postfix() which skips multiple ')' but doesn't do anything.
Your code is very hard to follow. Properly naming variables and functions and eliminating most of the globals (you don't actually need most of them) would help a great deal as would proper indentation and add a few spaces in expressions.
There are other minor issues not particularily worth mentioning. For example the covchar() and covnum() functions are much more complex than needed.
I've written a few postfix parsers over the years and I can't really follow what you are trying to do, which isn't to say the way you're trying is impossible but I would suggest re-examining at the base logic needed to parse the expression, particularly nested levels of brackets.

cout or printf which of the two has a faster execution speed C++?

I have been coding in C++ for a long time. I always wondered which has a faster execution speed printf or cout?
Situation: I am designing an application in C++ and I have certain constraints such as time limit for execution. My application has loads printing commands on the console. So which one would be preferable printf or cout?
Each has its own overheads. Depending on what you print, either may be faster.
Here are two points that come to mind -
printf() has to parse the "format" string and act upon it, which adds a cost.
cout has a more complex inheritance hierarchy and passes around objects.
In practice, the difference shouldn't matter for all but the weirdest cases. If you think it really matters - measure!
EDIT -
Oh, heck, I don't believe I'm doing this, but for the record, on my very specific test case, with my very specific machine and its very specific load, compiling in Release using MSVC -
Printing 150,000 "Hello, World!"s (without using endl) takes about -
90ms for printf(), 79ms for cout.
Printing 150,000 random doubles takes about -
3450ms for printf(), 3420ms for cout.
(averaged over 10 runs).
The differences are so slim this probably means nothing...
Do you really need to care which has a faster execution speed? They are both used simply for printing text to the console/stdout, which typically isn't a task that demands ultra-high effiency. For that matter, I wouldn't imagine there to be a large difference in speed anyway (though one might expect printf to be marginally quicker because it lacks the minor complications of object-orientedness). Yet given that we're dealing with I/O operations here, even a minor difference would probably be swamped by the I/O overhead. Certainly, if you compared the equivalent methods for writing to files, that would be the case.
printf is simply the standard way to output text to stdout in C.
'cout' piping is simply the standard way to output text to stdout in C++.
Saying all this, there is a thread on the comp.lang.cc group discussing the same issue. Consensus does however seem to be that you should choose one over the other for reasons other than performance.
The reason C++ cout is slow is the default sync with stdio.
Try executing the following to deactivate this issue.
ios_base::sync_with_stdio(false)
http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/
http://msdn.microsoft.com/es-es/library/7yxhba01.aspx
On Windows at least, writing to the console is a huge bottleneck, so a "noisy" console mode program will be far slower than a silent one. So on that platform, slight differences in the library functions used to address the console will probably make no significant difference in practice.
On other platforms it may be different. Also it depends just how much console output you are doing, relative to other useful work.
Finally, it depends on your platform's implementation of the C and C++ I/O libraries.
So there is no general answer to this question.
Performance is a non-issue for comparison; can't think of anything where it actually counts (developing a console-program). However, there's a few points you should take into account:
Iostreams use operator chaining instead of va_args. This means that your program can't crash because you passed the wrong number of arguments. This can happen with printf.
Iostreams use operator overloading instead of va_args -- this means your program can't crash because you passed an int and it was expecting a string. This can happen with printf.
Iostreams don't have native support for format strings (which is the major root cause of #1 and #2). This is generally a good thing, but sometimes they're useful. The Boost format library brings this functionality to Iostreams for those who need it with defined behavior (throws an exception) rather than undefined behavior (as is the case with printf). This currently falls outside the standard.
Iostreams, unlike their printf equivilants, can handle variable length buffers directly themselves instead of you being forced to deal with hardcoded cruft.
Go for cout.
I recently was working on a C++ console application on windows that copied files using CopyFileEx and was echoing the 'to' and 'from' paths to the console for each copy and then displaying the average throughput at the end of the operation.
When I ran the console application using printf to echo out the strings I was getting 4mb/sec, when replacing the printf with std::cout the throughput dropped to 800kb/sec.
I was wondering why the std::cout call was so much more expensive and even went so far as to echo out the same string on each copy to get a better comparison on the calls. I did multiple runs to even out the comparison, but the 4x difference persisted.
Then I found this answer on stackoverflow..
Switching on buffering for stdout did the trick, now my throughput numbers for printf and std::cout are pretty much the same.
I have not dug any deeper into how printf and cout differ in console output buffering, but setting the output buffer before I begin writing to the console solved my problem.
Another Stack Overflow question addressed the relative speed of C-style formatted I/O vs. C++ iostreams:
Why is snprintf faster than ostringstream or is it?
http://www.fastformat.org/performance.html
Note, however, that the benchmarks discussed were for formatting to memory buffers. I'd guess that if you're actually performing the I/O to a console or file that the relative speed differences would be much smaller due to the I/O taking more of the overall time.
If you're using C++, you should use cout instead as printf belongs to the C family of functions. There are many improvements made for cout that you may benefit from. As for speed, it isn't an issue as console I/O is going to be slow anyway.
In practical terms I have always found printf to be faster than cout. But then again, cout does a lot more for you in terms of type safety. Also remember printf is a simple function whereas cout is an object based on a complex streams hierarchy, so it's not really fair to compare execution times.
To settle this:
#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;
int main( int argc, char * argcv[] ) {
const char * const s1 = "some text";
const char * const s2 = "some more text";
int x = 1, y = 2, z = 3;
const int BIG = 2000;
time_t now = time(0);
for ( int i = 0; i < BIG; i++ ) {
if ( argc == 1 ) {
cout << i << s1 << s2 << x << y << z << "\n";
}
else {
printf( "%d%s%s%d%d%d\n", i, s1, s2, x, y, z );
}
}
cout << (argc == 1 ? "cout " : "printf " ) << time(0) - now << endl;
}
produces identical timings for cout and printf.
Why don't you do an experiment? On average for me, printing the string helloperson;\n using printf takes, on average, 2 clock ticks, while cout using endl takes a huge amount of time - 1248996720685 clock ticks. Using cout with "\n" as the newline takes only 41981 clock ticks. The short URL for my code is below:
cpp.sh/94qoj
link may have expired.
To answer your question, printf is faster.
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
using namespace std;
int main()
{
clock_t one;
clock_t two;
clock_t averagePrintf;
clock_t averageCout;
clock_t averagedumbHybrid;
for (int j = 0; j < 100; j++) {
one = clock();
for (int d = 0; d < 20; d++) {
printf("helloperson;");
printf("\n");
}
two = clock();
averagePrintf += two-one;
one = clock();
for (int d = 0; d < 20; d++) {
cout << "helloperson;";
cout << endl;
}
two = clock();
averageCout += two-one;
one = clock();
for (int d = 0; d < 20; d++) {
cout << "helloperson;";
cout << "\n";
}
two = clock();
averagedumbHybrid += two-one;
}
averagePrintf /= 100;
averageCout /= 100;
averagedumbHybrid /= 100;
cout << "printf took " << averagePrintf << endl;
cout << "cout took " << averageCout << endl;
cout << "hybrid took " << averagedumbHybrid << endl;
}
Yes, I did use the word dumb. I first made it for myself, thinking that the results were crazy, so I searched it up, which ended up with me posting my code.
Hope it helps,
Ndrewffght
If you ever need to find out for performance reasons, something else is fundamentally wrong with your application - consider using some other logging facility or UI ;)
Under the hood, they will both use the same code, so speed differences will not matter.
If you are running on Windows only, the non-standard cprintf() might be faster as it bypasses a lot of the streams stuff.
However it is an odd requirement. Nobody can read that fast. Why not write output to a file, then the user can browse the file at their leisure?
Anecdotical evidence:
I've once designed a logging class to use ostream operators - the implementation was insanely slow (for huge amounts of data).
I didn't analyze that to much, so it might as well have been caused by not using ostreams correctly, or simply due to the amount of data logged to disk. (The class has been scrapped because of the performance problems and in practice printf / fmtmsg style was preferred.)
I agree with the other replies that in most cases, it doesn't matter. If output really is a problem, you should consider ways to avoid / delay it, as the actual display updates typically cost more than a correctly implemented string build. Thousands of lines scrolling by within milliseconds isn't very informative anyway.
You should never need to ask this question, as the user will only be able to read slower than both of them.
If you need fast execution, don't use either.
As others have mentioned, use some kind of logging if you need a record of the operations.