setprecision applied to old C style code - c++

I know that in C++ I can use setprecision as follows:
streamsize prec = cout.precision();
cout << "Your grade is: " << setprecision(3) << finalGrade << setprecision(prec);
How can I adapt this to the following old style code, particularly when writing to a file?
for ( int k = 0 ; k < vector.size() ; k++ )
{
fprintf( myFile, "%i\t%f\t%f\n", k+1, vector[k].x, vector[k].y );
std::cout << vector[k].x << "\t" << vector[k].y;
}
What specifically I am confused about is the order in which setprecision(3) and setprecision(prec) appear, when there is more than one variable, like in the case of vector elements being written to a file...
Could somebody please help me understand this?
Thank you,

It was not clear from the question that you want the setprecision to modify how fprintf works; it's only clear from the comments.
This is impossible (at least, with the existing C++ standard library).
The stdio and iostreams systems are separate, mostly independent parts in C++. In addition, the iostreams stuff was standardized after the stdio stuff, so to support having setprecision affect fprintf would mean changing fprintf code, which no one wants to do.
To give an idea on how separate they are, look at ios_base::sync_with_stdio - a dedicated function to make fpritnf and operator<< interoperate.
To make your system work, you probably have to replace fprintf by operator<<. Another way would be adjusting the fprintf's format string, but you would have to add the obscure call to ios_base::sync_with_stdio to your code.

The way to indicate the number of decimals in fprintf is %.[number]f; in your case, for 3 decimals the code will be
fprintf( myFile, "%i\t%.3f\t%.3f\n", k+1, vector[k].x, vector[k].y );

Related

Most efficient way to output a newline

I was wondering what is the most efficient performant way to output a new line to console. Please explain why one technique is more efficient. Efficient in terms of performance.
For example:
cout << endl;
cout << "\n";
puts("");
printf("\n");
The motivation for this question is that I find my self writing loops with outputs and I need to output a new line after all iterations of the loop. I'm trying to find out what's the most efficient way to do this assuming nothing else matters. This assumption that nothing else matters is probably wrong.
putchar('\n') is the most simple and probably fastest. cout and printf with string "\n" work with null terminated string and this is slower because you process 2 bytes (0A 00). By the way, carriage return is \r = 13 (0x0D). \n code is Line Feed (LF).
You don't specify whether you are demanding that the update to the screen is immediate or deferred until the next flush. Therefore:
if you're using iostream io:
cout.put('\n');
if you're using stdio io:
std::putchar('\n');
The answer to this question is really "it depends".
In isolation - if all you're measuring is the performance of writing a '\n' character to the standard output device, not tweaking the device, not changing what buffering occurs - then it will be hard to beat options like
putchar('\n');
fputchar('\n', stdout);
std::cout.put('\n');
The problem is that this doesn't achieve much - all it does (assuming the output is to a screen or visible application window) is move the cursor down the screen, and move previous output up. Not exactly a entertaining or otherwise valuable experience for a user of your program. So you won't do this in isolation.
But what comes into play to affect performance (however you measure that) if we don't output newlines in isolation? Let's see;
Output of stdout (or std::cout) is buffered by default. For the output to be visible, options include turning off buffering or for the code to periodically flush the buffer. It is also possible to use stderr (or std::cerr) since that is not buffered by default - assuming stderr is also directed to the console, and output to it has the same performance characteristics as stdout.
stdout and std::cout are formally synchronised by default (e.g. look up std::ios_base::sync_with_stdio) to allow mixing of output to stdout and std::cout (same goes for stderr and std::cerr)
If your code outputs more than a set of newline characters, there is the processing (accessing or reading data that the output is based on, by whatever means) to produce those other outputs, the handling of those by output functions, etc.
There are different measures of performance, and therefore different means of improving efficiency based on each one. For example, there might be CPU cycles, total time for output to appear on the console, memory usage, etc etc
The console might be a physical screen, it might be a window created by the application (e.g. hosted in X, windows). Performance will be affected by choice of hardware, implementation of windowing/GUI subsystems, the operating system, etc etc.
The above is just a selection, but there are numerous factors that determine what might be considered more or less performance.
On Ubuntu 15.10, g++ v5.2.1 (and an older vxWorks, and OSE)
It is easy to demonstrate that
std::cout << std::endl;
puts a new line char into the output buffer, and then flushes the buffer to the device.
But
std::cout << "\n";
puts a new line char into the output buffer, and does not output to the device. Some future action will be needed to trigger the output of the newline char in the buffer to the device.
Two such actions are:
std::cout << std::flush; // will output the buffer'd new line char
std::cout << std::endl; // will output 2 new line chars
There are also several other actions that can trigger the flush of the std::cout buffering.
#include <unistd.h> // for Linux
void msDelay (int ms) { usleep(ms * 1000); }
int main(int, char**)
{
std::cout << "with endl and no delay " << std::endl;
std::cout << "with newline and 3 sec delay " << std::flush << "\n";
msDelay(3000);
std::cout << std::endl << " 2 newlines";
return(0);
}
And, per comment by someone who knows (sorry, I don't know how to copy his name here), there are exceptions for some environments.
It's actually OS/Compiler implementation dependent.
The most efficient, least side effect guaranteed way to output a '\n' newline character is to use std::ostream::write() (and for some systems requires std::ostream was opened in std::ios_base::binary mode):
static const char newline = '\n';
std::cout.write(&newline,sizeof(newline));
I would suggest to use:
std::cout << '\n'; /* Use std::ios_base::sync_with_stdio(false) if applicable */
or
fputc('\n', stdout);
And turn the optimization on and let the compiler decide what is best way to do this trivial job.
Well if you want to change the line I'd like to add the simplest and the most common way which is using (endl), which has the added perk of flushing the stream, unlike cout << '\n'; on its own.
Example:
cout << "So i want a new line" << endl;
cout << "Here is your new line";
Output:
So i want a new line
Here is your new line
This can be done for as much new lines you want. Allow me to show an example using 2 new lines, it'll definitely clear all of your doubts,
Example:
cout << "This is the first line" << endl;
cout << "This is the second line" << endl;
cout << "This is the third line";
Output:
This is the first line
This is the second line
This is the third line
The last line will just have a semicolon to close since no newline is needed. (endl) is also chain-able if needed, as an example, cout << endl << endl; would be a valid sequence.

Easiest/clearest way to read formatted data in C++

I'm reading in a file of space/newline delimited numbers. After trying stringstreams and ifstreams, it appears C++ hasn't improved much on fopen and fscanf for this simple task in terms of simplicity, readability, or efficiency.
What about robustness? Since I check that fscanf returned the number of items I expect, this doesn't seem like an issue. The only benefit I can think of is stringstream's giving you more options to handle a failure.
Here is a quick example using fscanf:
FILE * pFile;
pFile = fopen ("my_file.txt","r");
if( pFile == NULL ) return -1;
double x,y,z;
int items_read;
while( true )
{
items_read = fscanf( pFile, "%lf %lf %lf", x, y, z );
if( items_read < 3 ) break; // Checks for EOF (which is -1) or reading 1-2 numbers
std::cout << x << " " << y << " " << z << "\n";
}
NOTE: for extra security, could replace fopen/fscanf with fopen_s/fscanf_s in Visual Studio.
In my experience neither C nor C++ offer you "robust input that tolerates idiot users".
It is adequate for "well formed input where it's OK to say 'something wrong in your input, please fix it'...", but not for robust situations where you need to check everything carefully (e.g. someone putting two instead of three numbers on a line, so the whole rest of the data is happily acceped, but now all your z values are actually x values, and everything else is "shifted one").
In that case, you do need to write some functions that do the appropriate checking by reading a line, checking that it can fetch three numbers out of that line - or something like that. You may well find that using stringstream or something similar is adequate for checking that there are three valid numbers on the line, but just using f >> x >> y >> z; will obviously lead to the next line being used to satisfy whatever is missing on this line.

Issue when "fixed" stream manipulator is removed

I am new to C++, learning it by my self, and I am using the book "C++ how to program - 7th edition" from Deitel. Now, please have a look at the following code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double principle = 1000;
double amount;
double rate = 0.05;
cout << "Year" << setw(21) << "Amount on deposit" << endl;
cout << fixed << setprecision(2);
for(int years=1; years<=10; years++)
{
amount = principle * pow(1.0+rate,1.0);
cout << setw(4) << years << setw(21) << amount << endl;
}
}
When I removed the "fixed" stream manipulator, the output becomes stupid, which means, just ascii letters and numbers. When I insert it, the output comes without any problem. My question is, why is this happening? Is "fixed" mandatory for all the programs which has "double" type outputs? Please help.
And another thing. What are stream manipulators? As a Java developer, I thought these might be some kind of constant variables, but it is not! They are methods? Then why the brackets are not there? Please answer to this question too.
Thanks
The output does not "become stupid": you simply let your output stream choose the format for your floating-point numbers, and it picks scientific notation. This gives you 1e+03 (which means 1*10^3) instead of 1050.00. The use of fixed tells the stream that you do not want scientific notation; you could also use scientific to force the scientific format. Since the precise format depends depends on your application requirements, the choice to use fixed or scientific is ultimately up to you.
Manipulators like fixed are functions, but if you wanted the common () for it then it would look like this:
fixed(cout); //Instead of using the << or >> you pass the stream into the manipulator function.
See this reference for more on manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/
Also, fixed documentation can be found here:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
Hope this helps
It's not just ascii letter and numbers
1e+03 is scientific writing for 1*10^3 which is 1000
for reference:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
If you had chose a wider precision, your output would have been different without fixed.
cout << setprecision(6); // 6 instead of 2
Then your output would have looked more like you expected. (Incidentally, you should compute the compound interest by folding the interest earned back into the principle.)
Otherwise, with only setprecision(2), the formatter decides to use scientific notation in order to only display 2 digits of precision.
But, since you want the output to provide a fixed number of digits, what you have provided (both fixed and setprecision(2)) will do that.

which is faster, and which is more flexible: printf or cout? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
printf vs cout in C++
cin or printf??
I've always wondered about printf and cout.. which one is ultimately faster, and is it the most flexible as well (ie can print a range of variables, and output can be formatted)?
P.S.
I know this looks similar to 'printf' vs. 'cout' in C++ ,but i'm not really asking the same thing.
Short Answer
Faster : printf
More flexible : cout
Long answer
When compared to the sprintf family, the C++ streams are supposed to be slower (by a factor 6 if I recall an item of Exceptional C++, by Herb Sutter). Still, most of the time, you won't need this speed, but you need to be sure your code won't be bugged.
And it is easy to do something wrong with the printf family of functions, be it putting the wrong number of arguments, the wrong types, or even introduce potential security vulnerability (the %n specifier comes to mind) in your code.
Unless really wanting it (and then, it's called sabotage), it's almost impossible to get it wrong with C++ streams. They handle seamlessly all known types (build-ins, std::strings, etc.), and it's easy to extend it. For example, let's say I have an object "Coordinate3D", and that I want to print out its data:
#include <iostream>
struct Coordinate3D
{
int x ;
int y ;
int z ;
} ;
std::ostream & operator << (std::ostream & p_stream
, const Coordinate3D & p_c)
{
return p_stream << "{ x : " << p_c.x
<< " , y : " << p_c.y
<< " , z : " << p_c.z << " }" ;
}
int main(int argc, char * argv[])
{
Coordinate3D A = {25,42,77} ;
std::cout << A << std::endl ;
// will print "{ x : 25 , y : 42 , z : 77 }"
return 0 ;
}
The problem with the stream is that they are quite difficult to handle correctly when wanting to specify format of some data (padding spaces for numbers, for example), and that sometimes, you really really need to go fast. Then, either fall back to printf, or try some high-speed C++ alternatives (FastFormat comes to mind).
Edit: Note that Thomas' series of tests show interesting results (which I reproduced right now on my computer), that is: cout and printf have similar performances when one avoids using std::endl (which flushes the output in addition to outputing a \n).
Faster: printf
More typesafe and extensible: cout
Better: depends! I like printf more.
I'm not alone in thinking that the way C++'s cout does formatting is just epic fail.

Parse int to string with stringstream

Well!
I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution.
I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999].
As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream.
So my code looked like this:
// tempTotal is my int value I want converted.
void toString( int tempTotal, string &str )
{
ostringstream ss; // C++ Standard compliant method.
ss << tempTotal;
str = ss.str(); // Overwrite referenced value of given string.
}
and the function calling it was:
else
{
toString( tempTotal, store );
cout << loop1 << " x " << loop2 << "= " << store << endl;
}
So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there.
Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal.
All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know.
So even though I feel this is a really, really lame question, I just have to ask:
How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.
EDIT:
Wow. Seriously. This is kind of embarrassing. I forgot to set my tempTotal variable to something. It was uninitialized, so therefore I couldn't copy anything and the reason the program gave me either a 0 or nothing at all.
Hope people can have a laugh though, so I think this question would now be better suited for deletion since it doesn't really serve a purpose unless xD But thanks to everybody who tried to help me!
Have you tried just outputting the integer as is? If you're only converting it to a string to output it, then don't bother since cout will do that for you.
else
{
// toString( tempTotal, store ); // Skip this step.
cout << loop1 << " x " << loop2 << "= " << tempTotal << endl;
}
I have a feeling that it's likely that tempTotal doesn't have the value you think it has.
I know this doesn't directly answer your question but you don't need to write your own conversion function, you can use boost
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
//usage example
std::string s = lexical_cast<std::string>(tempTotal);
Try the following:
string toString(int tempTotal)
{
ostringstream ss;
ss << tempTotal;
return ss.str();
}
string store = toString(tempTotal);
If you want to output the integer, you don't even need to convert it; just insert it into the standard output:
int i = 100;
cout << i;
If you want the string representation, you're doing good. Insert it into a stringstream as you did, and ask for it's str().
If that doesn't work, I suggest you minimize the amount of code, and try to pinpoint the actual problem using a debugger :)
Short answer: your method to convert an int to a string works. Got any other questions?