Bernhard Hidding wrote:
Hello,
I want to combine a string with an integer. I work on SuSE 9.1 with g++. Why
does this piece of code not work?
#include <iostream.h>
#include <stdio.h>
#include <fstream.h>
#include <string>
...
intvar intg = 0;
std::string arraystring = "array" + intvar +".dat";
...
g++ gives the following error message:
error: invalid operands of types `const char*' and `const char[5]' to binary
`operator+'
Thanks for your help,
Bernhard
Because of precedence rules for addition of arrays and pointers. Also
because the string class has no constructors for converting from int to
string nor for appending an integer quantity.
In a string concatenation situation, the operator '+' is overloaded to
perform concatenation:
array_string = "array" + " hello";
which is equal to:
array_string = string("array").operator+(string(" hello"));
Applying the above to a string concatenated with an integer would
look like:
array_string = "array" + 4; /* numeric const or int variable */
array_string = string("array").operator+(4);
In order to accomplish what you want, the string class would
need a method of:
string& string::operator+(int);
which doesn't exist.
However, some non-standard string libraries have constructors
that can take integral arguments and convert them to strings.
So, assuming a specialized string class called AnsiString that
has such an operator, you would want:
AnsiString arraystring;
arraystring = "array" + AnsiString(intvar) + ".dat";
Look up istringstream and ostringstream. Another alternative
is to use sprintf.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book