|
-
July 17th, 2008, 12:59 PM
#1
<stdio.h> and <iostream>
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>?
-
July 17th, 2008, 01:22 PM
#2
Re: <stdio.h> and <iostream>
There's stringstreams, which do the same thing, but the <iostream> library doesn't have a concept of format strings per se.
-
July 20th, 2008, 01:43 PM
#3
Re: <stdio.h> and <iostream>
-
July 21st, 2008, 12:18 PM
#4
Re: <stdio.h> and <iostream>
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:
Code:
#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
-
July 21st, 2008, 02:44 PM
#5
Re: <stdio.h> and <iostream>
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.
-
July 21st, 2008, 02:57 PM
#6
Re: <stdio.h> and <iostream>
 Originally Posted by YAPP
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.
-
July 22nd, 2008, 07:09 PM
#7
Re: <stdio.h> and <iostream>
 Originally Posted by Jpsarapuu
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>.
-
July 22nd, 2008, 07:14 PM
#8
Re: <stdio.h> and <iostream>
You may find this article on the topic helpful. It compares all the standard ways of converting numbers to strings, and gives advanatges and disadvantages of each.
Old Unix programmers never die, they just mv to /dev/null
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|