|
-
Dec 10th, 2002, 09:27 AM
#1
Thread Starter
Addicted Member
Appending integers/numbers to strings
Hi, this should be a simple question, but I'm having a bit or a nightmare.
I'm trying to append a string with a number:
Code:
typedef basic_string<TCHAR> tstring;
tstring strThis = "My String";
strThis += ??;
Now, the first attempt is obviously to just append the number, but this appends the character with the ascii code of the number - which is really annoying.
What is the way to do this, as I dont want to have to add 48 to everything!
Thanks in advance.
HD
-
Dec 10th, 2002, 10:27 AM
#2
Frenzied Member
Try sprintf() to reformat the number.
-
Dec 10th, 2002, 11:00 AM
#3
Thread Starter
Addicted Member
Unfortunately I can't get that to work, as I'm using strings.
The strings dont work inside sprintf which was really annoying - it was the first thing I thought of as I used to be a C programmer.
I could reformat the number into a buffer - but I'm hoping there is a 'neater' way to do it.
Thanks anyway Jim.
HD
-
Dec 10th, 2002, 11:13 AM
#4
There is: stringstream:
Code:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int func(int i)
{
ostringstream oss;
oss << i;
string s = oss.str();
cout << s.c_str();
istringstream iss(s);
int j;
iss >> j;
cout << j;
s = "500";
iss.str(s);
iss >> j;
cout << j;
return j;
}
There it is. Header is <sstream>.
Input: basic_istringstream<typename character, typename traits = char_traits<character>, typename alloc = allocator<character> >
Output: basic_ostringstream<typename character, typename traits = char_traits<character>, typename alloc = allocator<character> >
Both: basic_stringstream<typename character, typename traits = char_traits<character>, typename alloc = allocator<character> >
char:
istringstream, ostringstream, stringstream
wchar_t: wistringstream, wostringstream, wstringstream
tchar:
typedef basic_istringstream<TCHAR> tistringstream;
typedef basic_ostringstream<TCHAR> tostringstream;
typedef basic_stringstream<TCHAR> tstringstream;
Derived from basic_istream/basic_ostream/basic_iostream, therefore the common << and >> overloads work.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Dec 10th, 2002, 11:16 AM
#5
Thread Starter
Addicted Member
Thats what I've been looking for (I think).
Cheers mate.
HD
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
|