What is it that I'm just not getting?

How would I got about appending an integer to the end of a string?

I'm a former java programmer, so I would use stringName = stringName + intName;

What is the C++ equivalent.

Thanks.
Last edited on
I'm not a java programer so I cannot comment on the differences. It does seem that Java does a lot for you. With C and C++ you have to do it yourself. Adding an int on to the end of a string cannot be done without a bit of work because they are different types.
You have to convert the int to a string or char array first before concatenation. Java obviously does all the work for you.

For example, the old 'C' way of doing this would be sprintf(). This will create a char array from you int
1
2
3
4
5
6
int intName = 16;
char chArr[3];

sprintf(chArr,"%d\n", intName);

stringName.append(chArr);


For C++ there is no standard way of doing this that doesn't involve embedding the above code (or something similar) into a class. I expect Boost has something to do it and maybe some other 3rd part libraries.

The core C++ language is 64 key words. There is the Standard Template Library (STL) that nearly every C++ compiler supports. There are 3rd party libraries for extended functionality (like Boost). Java appears to be much more regimented. C and C++'s strength is the flexibility it gives the person writing the code. There are so many ways of doing the same thing, each one has benefits and drawbacks, you can 'tune' the code to fit the application.

This is why nothing has managed to replace them as the best general purpose languages out there.
Ok.
There doesn't seem to be any function called 'sprintf' in c++?
Also, how can I convert a string (object) into a char array, and vice versa?

Last edited on
closed account (z05DSL3A)
http://www.cplusplus.com/reference/string/string/
For C++ there is no standard way of doing this that doesn't involve embedding the above code (or something similar) into a class. I expect Boost has something to do it and maybe some other 3rd part libraries.

That's not quite true. Streams (and, therefore, stringstreams) are designed for exactly this task. In fact, using the C functions is bad style at best.
1
2
3
4
5
6
7
std::string s = "Hello, World!";
std::stringstream ss(s);
int i = 42;
ss<<" "<<i;
s = ss.str();
const char* c = s.c_str();
...



There is the Standard Template Library (STL) that nearly every C++ compiler supports.

The STL is contained in the C++ standard (ISO 14882). Thus, a compiler without the stl is *not* an implementation of the language.
However, C++ main advantage over any other language known to me is the wide range of supported paradigms. Java forces you to use classes. C++ doesn't. You can also code functional. Or generic. Or combine whatever you want to combine. Plus, you have "unfiltered" acces to low-level functions and types (try to implement fast and robust algorithms based on IEEE 754 arithmetic in Java - good luck with that - the same goes for operating system components like device drivers, filesystems or complete kernels...)
On the other hand, for many applications these functions are not needed and many programmers are happy when they have their OO-language. Thus, why not use it?
Thanks. That helps alot.
exception:
Why is using C functions bad style? This is an honest question, not trolling. Is it because it does not make use of the possibilities C++ provides?
I think there is nothing wrong in using C style function and you always get a mix of these when you continue developing an old product.
But when you start from scartch and you intend to write pure C++ program then use STL because you are inheritng from ISO standard and others can follow your code nicely
Using C functions in C++ is not *always* "bad style". However, whenever C++ provides the means to do something also implemented in C, you should prefer the C++ version. A '\0'-terminated character array can lead to serious problems, both regarding security and debugging effort - just write one char to many... 'printf' and 'scanf' have a syntax which is hard to read and to debug, for a function has to output a type it knows nothing about except the 'typename' the programmer specified. This is either redundant (if there is no error) or contains an error, both are Bad Things. operator<< can be defined by the implementer of the type, and c++ automatically calls the right output function.
The same goes for C-style casts, where you can cast away constness without complaint. Or, how do you know if (int) 2.0f is 2 or whatever number a 2.0 as float would be as an int? With static_cast and reinterpret_cast, this becomes quite clear (and you have to know what you are doing when you use const_cast, the only C++-way to get rid of the const specifier)

Also, if you write code, reuse algorithms whenever possible - espectially when they are from the stl. This is something often overlooked by novice programmers. Consider:
1
2
3
4
5
6
7
std::vector<std::string> v;
bool is_in_v(std::string s)
{
  for(unsigned int i=0; i<v.size(); i++)
    if(s==v[i]) return true;
  return false;
}

What are the problems or could be done better?

2: 's' should be passed as a const reference. This is (a) faster and (b) cannot lead to an exception, what could happen with an implicit type conversion
4: v.size() is evaluated everey loop cycle (might be optimized away, then again, why rely on it?)
4: i++ has to return the old value of i. ++i would be the better choice, as it avoids an unneccessary temorary object (cannot be optimized away in the general case, since pre- and postincrement might have completely different semantics with user-defined types)

If the author had written
1
2
if(std::find(v.begin(), v.end(), "Hello, World!") != v.end())
  // "Hello, World!" is in v... 

none of these problems would have occurred, it would be easier to read, it is guaranteed to be bug-free and if you change the container type of v this line does not need to be modified.
This might be constructed, yes, but how many of the questions here would not have been asked if people would start to use std::for_each etc. appropriately? Half of them?

So, in essence, I use the term "good style" for code which is efficient, easy to read and maintain and "hard to get wrong" (try to put an error in the second code which does not lead to an compiler error and is not *obviously* wrong - good luck)

Edit

you always get a mix of these [C & C++] when you continue developing an old product.

Of course, if you don't want to edit the old code. Then again, if it is not self-contained, it might be time for a re-write. And the interface of self-contained C-code can easily be satisfied with the means of C++ without introducing C-style in the new code (that is one of the main reasons why things std::string::c_str() do exist, after all)
Last edited on
First of all, I had forgotten about stringstreams, having not used them in a long time.

Second, there is nothing wrong with using 'C' functions in C++. C++ was designed to integrate with C, and C++ is in fact a superset of C. If you look inside classes like stringtream you will eventually find C code, buried underneath all the exception handling and operator overiding.

Using the likes of STL over the likes of C stdlib functions allows you to make use of all the extra ability C++ has over C, without having to write it yourself, and makes your code more easily integrated into other C++ code. However, saying that using the C API is tantamount to bad practice, is a complete nonsense.

The STL is contained in the C++ standard (ISO 14882). Thus, a compiler without the stl is *not* an implementation of the language.


There are several C++ compilers specifically for embedded applications that do not include STL because of size issues. Saying they are not an implementation of the C++ language is just semantics.

EDIT: I take some of the annoyance out of my post having read exceptions post above that clarifies the use of the term 'good style'... and I fully agree with what exception has to say.
Last edited on
There are several C++ compilers specifically for embedded applications that do not include STL because of size issues. Saying they are not an implementation of the C++ language is just semantics.

Well, I would argue that that depends. I wrote an "operating system kernel" (well, something that could be booted from GRUB, read the MBR & extended partitions, search files in the ext2 fs and provide a very very basic shell interface which allowed the execution of statically linked elf-binaries - at least, it had multithreading...) in what I woluld argue is not C++: you don't have the STL. You don't have exceptions. You don't have builtin-functions. You don't have RTTI. You obviously don't have operators new and delete. Is this still C++? If you say no, why? What would you need in order to call it C++? If yes, what else would you have to take from it?

I have come to a usage-level (in terms of frequency) of the stl, where even a changed exception guarantee in the wrong place could make me go crazy (just imagine vector::push_back() not having the strong guarantee anymore). So for me the lack of the stl in c++ is definitely not "semantics". And when my supervisor asks me how longe I need to implement functionality xy in C++, my analysis is highly dependent on the fact that I know how to faciliate the stl algorithms - having to implement, lets say quicksort, on my own would undoubtetly tiple the development time (you don't have just to implement it, you have to test and debug it, too. And before writing it, you think 'Oh no, not a sorting function again... isn't there another way?'. And by the time you realize that the answer is 'no', I would be half finished with my task if I used the stl).

So, while one could argue that a "slim" version of C++, lacking whatever functionality, is still mainly C++. Then, C++ is well suited for many embedded or operating system development applications. However, I consider this a special case and assume that someone using "C++ without ..." is making that clear - and knows about the consequences.
Ok?
I'm just a 17 year old ,living in South Africa, who want to learn the basics of C++..
Most of the stuff you guys are discussing above is far beyond my level of understanding! I just want to know the best/easiest way to append an integer to a string.
Topic archived. No new replies allowed.