I'm doing a program that involves putting numbers into an array and then taking those numbers from the array and putting them into a string.
I've deduced that I need to convert the numbers into a char and put the char into the string individually, but when i use '0' + number or char(number), it doesn't change it. I still get @'s and x's.
fwd = fwd + char(num [fill]);
1 2
conv = '0' + num[fill];
fwd = fwd + conv
These are what I tried. conv is a char, num[fill] is an int array, and fwd is a string
Yes. stringstream is a type defined in the header file <sstream>. It is a type of iostream (like cout and cin) so it works the same. The difference is that a string stream isn't attached to the screen or keyboard, it's attached to a string (working as a buffer.) You can then call the method ss_var.str() (where ss_var is the name of your stringstream) to get that buffer.
Think about the code
1 2 3
int num[N] = { 1,2, 4, 2, 0, 5 };
for( int i = 0; i < N; ++i )
cout << num[i];
124205
So instead of printing them to screen, you print them to a string. Then you can get that string with the str() method.
Is s a string, or is s middle ground? What I need is something that will add the numbers of my array to one string and then add them in reverse to another string. How I get the numbers out of my array is easy enough. My biggest issue is trying to convert those numbers into a string. I see the s.str(), but that only looks like it will output the string of s. If I did fwd = s.str() would I still get the same result?
FYI pushing integers through a stringstream is not the most efficient method by far, but it is the easiest to learn and understand. Your most vocal resistance will likely come from old C purists. This trick works for any kind of number-to-string conversion in C++ that would, in Java, use one of the static Integer.toString(int) or similar functions.
As Mathhead200 noted above, you will need at least the following includes to make this work:
1 2
#include <sstream> // for stringstream type
#include <string> // for string type
Note also that if you're displaying numbers and need to show an explicit sign for both positive and negative numbers, you can use the following trick:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string foo( int i )
{
stringstream buf ( stringstream::out ) ; // Creates an output-only stream.
buf << ( i >= 0 ? "+" : "" ) // Inserts a plus sign only if it's needed.
<< i ;
return buf.str() ;
}
int main()
{
for( int i = -2 ; i < 3 ; i++ )
cout << foo(i) << endl ;
return 0 ;
}