Click to See Complete Forum and Search --> : <stdio.h> and <iostream>
Jpsarapuu
July 17th, 2008, 12:59 PM
Hi!
I'm quite used to handling data with <iostream> library.
In <stdio.h> there is a function called sprintf() that writes formatted data to a string. Does anyone know if there is a similar function in <iostream>?
Lindley
July 17th, 2008, 01:22 PM
There's stringstreams, which do the same thing, but the <iostream> library doesn't have a concept of format strings per se.
Jpsarapuu
July 20th, 2008, 01:43 PM
OK thanks.
jlou
July 21st, 2008, 12:18 PM
You can format your output to any stream (whether it is an iostream or a stringstream) using manipulators from <iomanip>. For example, if you want your number output in hexadecimal with at least eight characters you might use:#include <iostream>
#include <iomanip>
int main()
{
int val = 123456789;
std::cout << "0x";
std::cout << std::setw(8) << std::setfill('0');
std::cout << std::hex << val << '\n';
}
// output:
// 0x075bcd15
YAPP
July 21st, 2008, 02:44 PM
Note that if you're using C++ and not C, you should include <cstdio> instead of <stdio.h>, because sometimes <stdio.h> might be non-standard.
jlou
July 21st, 2008, 02:57 PM
Note that if you're using C++ and not C, you should include <cstdio> instead of <stdio.h>, because sometimes <stdio.h> might be non-standard.
Technically, <stdio.h> is standard in C++, so it will work on any standards-compliant compiler. It is deprecated, however, and you're right that you should use <cstdio> instead.
why2jjj
July 22nd, 2008, 07:09 PM
Hi!
I'm quite used to handling data with <iostream> library.
In <stdio.h> there is a function called sprintf() that writes formatted data to a string. Does anyone know if there is a similar function in <iostream>?
With regards to <stdio.h> and sprintf(), if you are not aware, you should be using snprintf() instead, as the 'n' means there is a parameter used to limit the max amount of characters written into the array. It's a more secure usage (though it doesn't prevent you from sticking in a MAX that is larger than your array).
But I am not aware of a C++ equivalent.
I'll take a stab at C++ suggestions: using setbuf() in <cstdio> to set up a buffer for writing re-direction, stringstream in <iostream>.
HighCommander4
July 22nd, 2008, 07:14 PM
You may find this article (http://www.gotw.ca/publications/mill19.htm) on the topic helpful. It compares all the standard ways of converting numbers to strings, and gives advanatges and disadvantages of each.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.