String Library & Appending Integer :: C++

Status
Not open for further replies.
Hi.

I am stuck with an intesting problem with the string library. Let say declare a string (empty). To start out, I append a statement. Afterward, I want to append an integer and end it with a char. For example:

string strTemp;

for (int i = 0; i < 5; ++i)
{
strTemp += "Count down: ";
strTemp += i; // Problem!
strTemp += '...";
cout << strTemp.c_str() << endl;
}

The output of the code above will looking something like:

Cout download: *character that 0 represents*
Cout download: *character that 1 represents*
Cout download: *character that 2 represents*
Cout download: *character that 3 represents*
Cout download: *character that 4 represents*

The output I want is:

Cout download: 0
Cout download: 1
Cout download: 2
Cout download: 3
Cout download: 4

Is there a way to append or concatenate an integer into a string variable and have the string variable store the integer as an integer instead of the ACSII character the integer represents?

Thanks,
Kuphryn

P.S. I experience the same problem with STL container. Furthermore, the problem remains even if I switch from a string to a vector<int>. It seems the two do not mix.
 
I would use sprintf for this sort of thing. Yay for C. ^_^

(I paste together strings like this:)

code:<HR>
Code:
commandstring = malloc(
            strlen(argv[1])
            + strlen(magicstruct.ff_name)
            + strlen(finalname)
            + 3
        );
        if (commandstring == NULL) {
            printf("Aieeee!\n");
            exit(EXIT_FAILURE);
        }<P>        strcpy(commandstring, argv[1]);
        strcat(commandstring, " ");
        strcat(commandstring, magicstruct.ff_name);
        strcat(commandstring, " ");
        strcat(commandstring, finalname);
--
Stephan T. Lavavej
http://stl.caltech.edu
 

Catfish

Ars Tribunus Angusticlavius
9,954
I'm slightly confused by the string implementation myself - there are a lot of different classes involved, and multiply ways of doing things. So, this may not be the right way, but this is the way I do it:
code:<HR>
Code:
int x = 1;
CString filename = "screenshot";
filename.AppendFormat("%d.bmp",x);
So, this creates a CString containing "screenshot1.bmp".

'%d' represents a decimal integer, and so is replaced by the first variable after the initial string in AppendFormat().

I believe that CString is a MFC-specific class. Try sprintf() for similar functionality with non-MFC code (I think it's C-code, not C++....).

[EDIT : Ah, Stephan beat me to it.

Alternatively, if you want proper C++ implementation, without MFC or plain ol' C code, use streams.
code:<HR>
Code:
        int x=10;
	ostringstream stringInt;
	osa << x;
	string temp = "FPS : " + osa.str();
which produces a string containing "FPS : 10"
]
 
What about:
code:<HR>
Code:
#include <string>
#include <iostream><P>using namespace std;<P>int main()
{
	string strTemp;<P>	for (int i = 0; i < 5; ++i)
	{
		strTemp = "Count down: ";	//have to reset this to empty string
		strTemp += char(i + '0'); // Problem any more?
		strTemp += "...";
		cout << strTemp.c_str() << endl;
	}
}

Edit: Catfish's ostingsream method is nicer, I think.

[This message was edited by BlackClaw on December 24, 2001 at 15:42.]
 
Oops.

After discovering that itoa isn't ANSI, just use sprintf:
code:<HR>
Code:
#include <string>
#include <cstdio>
#include <iostream><P>using namespace std;<P>int main()
{
	string strTemp;
	char buf[11];		//reverting to the C style, and works for 32-bit integers only (would have to be, buf[22], for 64-bit ints)<P>	for (int i = -2; i < 15; ++i)
	{
		strTemp = "Count down: "; //have to reset this to empty string
		//itoa(i, buf, 10);		//not ANSI, apparently. well, I learned something about C today
		sprintf(buf, "%d", i);
		strTemp += string(buf); // Problem any more?
		strTemp += "...";
		cout << strTemp.c_str() << endl;
	}
}

Uh, for completeness's sake, the all-C++ standard library way:
code:<HR>
Code:
#include <sstream>
#include <string>
#include <iostream><P>using namespace std;<P>int main()
{
	string strTemp;
	stringstream ss;
	//char buf[11];		//reverting to the C style, and works for 32-bit integers only (would have to be, buf[22], for 64-bit ints)<P>	for (int i = -2; i < 15; ++i)
	{
		strTemp = "Count down: "; //have to reset this to empty string
		ss.str("");		//clear other buffer, too
		ss << i;
		strTemp += ss.str();
		strTemp += "...";
		cout << strTemp.c_str() << endl;
	}
}

Finally, see PeterB's message about this (particularly the generic C++ cast he provides).

[This message was edited by BlackClaw on December 24, 2001 at 16:27.]
 
Catfish:

Oh! Life saver! The ostringstream is the solution! It is just amazing. It does exactly what I am trying to get the code to do. There is one slight problem. I cannot get the ostringstream to clear.

Referring to the code above, using ostringstream would look like:

Cout download: 0
Cout download: 01
Cout download: 012
Cout download: 0123
Cout download: 01234

I tried:

int x = 1;
string strXYZ;
ostringstream osTemp;
osTemp << x;
strXYZ += osTemp.str();

osTemp.clear() // This does not seem to erase it.

Kuphryn
 
..str("");

Where did you get that from?

Kuphryn
Straight from STL docs....
void
str(const string_type& str);

Clears the underlying string buffer and copies the string object str into it. If the opening mode is in, initializes the input sequence to point to the first character of the buffer. If the opening mode is out, initializes the output sequence to point to the first character of the buffer. If the opening mode is out | app, initializes the output sequence to point to the last character of the buffer.
So passing an empty string just clears the buffer. Another (cleaner) solution is to declare the ostringstream inside the loop so that it gets reconstructed every time around. This might be slightly slower, but there's no chance of you forgetting to clear it.
 
I want to clarify that Nicolai Josuttis' The C++ Standard Library does in fact discusses how to clear the ostringstream. I was so excited I missed that paragraph.

strm.str("");

"The first line written to os are each terminted with endl." ...

This book is the best for the standard library. The members in this forum as well as some other programming forums are as insightful as well.

Kuphryn
 
I would like to know the difference between:

- stringstream
- istringstream
- ostringstream

I am using ostringstream to solve the problem I posted. Is it possible to use stringstream instead, or maybe istringstream?

Kuphryn
Same difference there is between fstream, ifstream, and ofstream. stringstream opens the underlying buffer for input and output. istringstream opens if for input only. ostringstream opens it for output only.

You problem could be solved with a stringstream, but not with an istringstream. istringstream is useful when you get a string and need to extract values from it (command-line arguments come to mind).
code:<HR>
Code:
string aString = "12 34 45 67 34 23";
...
istringstream is(aString);
while (is)
{
    int num;
    is >> num;
    // do something with the number
}
 
Status
Not open for further replies.