Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];

   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

Answer from Lightness Races in Orbit on Stack Overflow
Discussions

Concatenate a string with an int. - C++ Forum
Concatenate a string with an int. ... Hello people, I'm having trouble trying to concat a string with an int type. I want to put the value of the int inside the string. The ideia is something like this: The console should print: The number is 265 But, doesn't matter what I try, the compiler (Dev-C++) always says: Or anything else saying that it's not possible... What should I do to make this works? ... A string and ... More on cplusplus.com
🌐 cplusplus.com
August 6, 2008
Concating String and Integer
I am unable to concat string like following int i = 12; Serial.println("p"+i+"p"); It is giving me an error like "invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+' " i have met this when trying to send a GET request like following client.get("192.168.1.2/ac... More on forum.arduino.cc
🌐 forum.arduino.cc
17
0
May 16, 2017
c++ - How to concatenate a std::string and an int - Stack Overflow
I thought this would be really simple, but it's presenting some difficulties. If I have std::string name = "John"; int age = 21; How do I combine them to get a single string "John21... More on stackoverflow.com
🌐 stackoverflow.com
Strings and Integers. Beginner question
This gets a little complicated but it's a good thing to learn! Sometimes it pays to copy stuff from what isn't working, then copy stuff that is working into a different window and compare them on top. Let's do that right now: Console.WriteLine("You are " num1 - num2 " years old".); // Error Console.WriteLine("Hello " + name + " you are " + age); // Works If you look closely, you'll see the main difference is the + sign. Let's stop doing more than one thing at a time and step backwards and talk about how we "join" strings together. (The fancy word for this is "concatenation"). In C#, the + operator is what we call "overloaded", that means it can do more than one thing. If the left-hand side is a number, it expects a number on the right-hand side and will do mathematic addition on the numbers. If the left-hand side is a string, it expects a string on the right-hand side and will "concatenate" the strings. For example: int numbers = 1 + 1; // 2 string digits = "1" + "1"; // "11" This is why the "" around strings is very, very important, it helps C# understand what a bare digit like "1" means. THE ORDER MATTERS. If there is a number on the left, whatever is on the right MUST be a number or something C# will automatically convert to a number to work. If you put a number on the left and a string on the right, it won't work, because C# can't and won't auto-convert strings to numbers: int numbers = 1 + "1"; // Error. C# insists you manually convert numbers. But if a string is on the left, C# wants a string on the right. Since every object in .NET has a ToString() method, this will usually work even if this looks a little confusing. string digits = "1" + 1; // "11" So in your first example, you tried to build this string: "You are " num1 - num2 " years old". You needed to have a + sign between the strings and the numbers. Since there is a string on the left side, C# will automatically convert the numbers in the middle to strings: Console.WriteLine("You are " + num1 - num2 + " years old."); There are other ways to do this. There's a concept of "formatting" strings in C#, where you can create placeholders in a string to show where you want to put values and later describe the values you want there. Usually you use the String.Format() method to do this, but it's so common Console.WriteLine() has some parameters that copy that syntax. So you could have written this: Console.WriteLine("You are {0} years old.", num1 - num2); People tend to prefer this approach because it makes it easier to see where spaces go in the string. This became so common in .NET, we have a shortcut syntax for it. If you use $"" to enclose a string, you are allowed to use variables and expressions inside {} and they will be converted to strings: Console.WriteLine($"You are {num1 - num2} years old."); There are a lot of fancy things you can do with string formatting, but this is enough for one lesson! More on reddit.com
🌐 r/csharp
11
4
March 24, 2022
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "c howtos" › "how to concatenate string and int in c"
How to Concatenate String and Int in C | Delft Stack
February 12, 2024 - Moving on to the main function, we declare a constant character pointer str1 pointing to the string hello there and an integer n1 initialized with the value 1234. Two character arrays are then declared: num, which will be used to store the string representation of n1, and buffer, a destination string buffer for the concatenated string.
🌐
Cplusplus
cplusplus.com › forum › beginner › 3405
Concatenate a string with an int. - C++ Forum
August 6, 2008 - You can't concatenate them. You must first convert the int to a string. You can have cout do it for you: cout << "The number is " << myInt; or you can #include <sstream> and use a string stream:
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Concating String and Integer - Programming - Arduino Forum
May 16, 2017 - I am unable to concat string like following int i = 12; Serial.println("p"+i+"p"); It is giving me an error like "invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+' " i have met this w…
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 114440-how-combine-string-integer.html
HOw to combine a String with an Integer
April 6, 2009 - would work if you use char s[NN] = "Ravi", where NN is big enough to hold the string "Ravi", the length of the number and the terminating zero, so 16 should be OK. [/code] in my case it didn't work because itoa takes 3 arguments. ... here i is the integer to be converted and after conversion this string gets stored in s.base is the base of the integer like decimal,binary,octal etc.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-concatenate-a-std-string-and-an-int-in-cplusplus
How to concatenate a std::string and an int in C++?
April 22, 2025 - #include <iostream> #include <sstream> ... to string type using to_string function. Then, we can simply use the + operator to combine first string and second string....
Find elsewhere
Top answer
1 of 16
1385

In alphabetical order:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. (ditto)
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms
2 of 16
323

In C++11, you can use std::to_string, e.g.:

auto result = name + std::to_string( age );
🌐
GeeksforGeeks
geeksforgeeks.org › c language › concatenating-two-strings-in-c
Concatenating Two Strings in C - GeeksforGeeks
It can be used for concatenating two strings by using the source string as formatted string and destination string as string buffer. C · #include <stdio.h> int main() { char s1[20] = "Hello "; char s2[] = "Geeks"; // Concatenate str1 and str2 using sprintf sprintf(s1 + strlen(s1), "%s", s2); printf("%s\n", s1); return 0; } Output ·
Published: July 12, 2025
🌐
W3Schools
w3schools.com › cs › cs_strings_concat.php
C# String Concatenation
C# uses the + operator for both addition and concatenation. Remember: Numbers are added. Strings are concatenated. If you add two numbers, the result will be a number: int x = 10; int y = 20; int z = x + y; // z will be 30 (an integer/number)
🌐
CodeGuru Forums
forums.codeguru.com › showthread.php
Thread: how do i concatenate a string with an integer?
November 8, 2006 - how do i concatenate a string with an integer in C? i tried str += i; it didnt work, i also tried str = " " + i; didnt work either
🌐
Reddit
reddit.com › r/csharp › strings and integers. beginner question
r/csharp on Reddit: Strings and Integers. Beginner question
March 24, 2022 -

So I made this and it didn't work

https://i.imgur.com/73GS95Z.png

I believe it was because on Line I tried to concatenate (is that the right term) strings with an integer???

 

I converted the integer into string first and this time it worked.

https://i.imgur.com/MP2octX.png

Ok. Fine.

 

Now I'm in the methods section of this tutorial I'm following, and the way we did it, we combined strings and integers in a single WriteLine and it still worked perfectly (see Line 22)

https://i.imgur.com/eY8A12y.png

I'm not sure why it worked this time. Can someone please explain?


ED

Thank you for the answers

Top answer
1 of 5
29
This gets a little complicated but it's a good thing to learn! Sometimes it pays to copy stuff from what isn't working, then copy stuff that is working into a different window and compare them on top. Let's do that right now: Console.WriteLine("You are " num1 - num2 " years old".); // Error Console.WriteLine("Hello " + name + " you are " + age); // Works If you look closely, you'll see the main difference is the + sign. Let's stop doing more than one thing at a time and step backwards and talk about how we "join" strings together. (The fancy word for this is "concatenation"). In C#, the + operator is what we call "overloaded", that means it can do more than one thing. If the left-hand side is a number, it expects a number on the right-hand side and will do mathematic addition on the numbers. If the left-hand side is a string, it expects a string on the right-hand side and will "concatenate" the strings. For example: int numbers = 1 + 1; // 2 string digits = "1" + "1"; // "11" This is why the "" around strings is very, very important, it helps C# understand what a bare digit like "1" means. THE ORDER MATTERS. If there is a number on the left, whatever is on the right MUST be a number or something C# will automatically convert to a number to work. If you put a number on the left and a string on the right, it won't work, because C# can't and won't auto-convert strings to numbers: int numbers = 1 + "1"; // Error. C# insists you manually convert numbers. But if a string is on the left, C# wants a string on the right. Since every object in .NET has a ToString() method, this will usually work even if this looks a little confusing. string digits = "1" + 1; // "11" So in your first example, you tried to build this string: "You are " num1 - num2 " years old". You needed to have a + sign between the strings and the numbers. Since there is a string on the left side, C# will automatically convert the numbers in the middle to strings: Console.WriteLine("You are " + num1 - num2 + " years old."); There are other ways to do this. There's a concept of "formatting" strings in C#, where you can create placeholders in a string to show where you want to put values and later describe the values you want there. Usually you use the String.Format() method to do this, but it's so common Console.WriteLine() has some parameters that copy that syntax. So you could have written this: Console.WriteLine("You are {0} years old.", num1 - num2); People tend to prefer this approach because it makes it easier to see where spaces go in the string. This became so common in .NET, we have a shortcut syntax for it. If you use $"" to enclose a string, you are allowed to use variables and expressions inside {} and they will be converted to strings: Console.WriteLine($"You are {num1 - num2} years old."); There are a lot of fancy things you can do with string formatting, but this is enough for one lesson!
2 of 5
4
Well - your first picture is missing the '+' symbols that would actually concat your string. (Your other pictures contain the symbol - and thus compile)
🌐
YouTube
youtube.com › watch
How to Concatenate a String with an Integer in C - YouTube
Learn how to effectively concatenate strings and integers in C programming, including valuable tips on using macros and functions for GPIO manipulation.---Th...
Published: May 27, 2025
Views: 7
🌐
SheCodes
shecodes.io › athena › 24756-how-to-concatenate-a-string-with-an-integer-in-c
[C++] - How to concatenate a string with an integer in C++? | SheCodes
Learn how to use std::to_string() function in C++ to concatenate a string with an integer. ... Create a program to accept a string from the user and then display the number of words,spaces and sentences in a string and count the number of words ...
Top answer
1 of 3
33

ToString usage

No, you shouldn't use ToString here.

String concatenation automatically transforms non-strings into strings, which means that your two variants are nearly¹ identical:

When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

Source: C# Language Specification: Addition operator, MSDN.

On the other hand, the first one (without ToString):

  • Is shorter to write,
  • Is shorter to read,
  • Is easier to maintain and:
  • shows exactly the intention of the author: to concatenate strings.

So prefer the first one.

Under the hood

What is also interesting is to see what happens under the hood. One of the ways to see it is to watch the IL code within LINQPad. This program:

void Main()
{
    var a = 3;
    var b = " Hello";
    var c = a + b;
    Console.WriteLine(c);
}

is translated to the following IL:

IL_0001:  ldc.i4.3    
IL_0002:  stloc.0     // a
IL_0003:  ldstr       " Hello"
IL_0008:  stloc.1     // b
IL_0009:  ldloc.0     // a
IL_000A:  box         System.Int32
IL_000F:  ldloc.1     // b
IL_0010:  call        System.String.Concat
IL_0015:  stloc.2     // c
IL_0016:  ldloc.2     // c
IL_0017:  call        System.Console.WriteLine

See that System.String.Concat? That means that the original code can be written also like that, which translates into exactly same IL:

void Main()
{
    var a = 3;
    var b = " Hello";
    var c = string.Concat(a, b); // This is the line which was changed.
    Console.WriteLine(c);
}

When you read the documentation of string.Concat(object[]), you may learn that:

The method concatenates each object in args by calling the parameterless ToString method of that object; it does not add any delimiters.

This means that ToString is redundant. Also:

String.Empty is used in place of any null object in the array.

Which handles nicely the case where some of the operands are null (see the footnote 1).

While in the last example, concatenation was translated into string.Concat, one should also highlight compiler optimizations:

var a = "Hello " + "World";

is translated into:

ldstr       "Hello World"
stloc.0

On the other hand:

var a = string.Concat("Hello ", "World");

is translated into:

ldstr       "Hello "
ldstr       "World"
call        System.String.Concat
stloc.0

Other alternatives

There are of course other ways to concatenate string representations of objects in C#.

  1. StringBuilder is used when you need to do a lot of concatenation operations and helps reducing the number of intermediary strings created. Deciding whether you should use a StringBuilder or an ordinary concatenation may not be easy. Use a profiler or search for relevant answers on Stack Overflow.

    Using StringBuilder has a major drawback of making the code difficult to read and maintain. For simple cases as the one in your question, StringBuilder is not only harmful to the readability of the code, but also useless in terms of performance.

  2. string.Join should be used when you need to add delimiters.

    Obviously, never use string.Join with an empty delimiter to concatenate strings.

  3. string.Format can be used when string templating is preferred to string concatenation. One of the cases where you may prefer that is when the message may be localized, as suggested in the answer by kunthet.

    Using string.Format has several drawbacks which makes it unsuited for simple cases like yours:

    • With simple "{0}" placeholders, it is often unclear which parameter goes where. It is frequent to mistakenly reverse the parameters or to forget one. Luckily, C# 6 finally introduces string interpolation which solves this problem.

    • Runtime performance may degrade. Of course, don't assume string.Format is always slower. If performance matters, measure two approaches and determine which one is faster based on your actual results instead of assumptions.

    • The code is slightly longer to write, longer to read and harder to maintain, although this is extremely minor and shouldn't bother you too much.


¹ The difference appears when one of the objects is null. Without ToString, a null is replaced by an empty string. With ToString, a NullReferenceException is thrown.

2 of 3
15

Instead, you should use string formatter. It's easier to format your number into string representation or localization. e.g.:

string expression = string.Format("Expression: {0} + {1} = {2}", a, b, sum);

More info on MSDN.

However, string formatter is less readable (and maybe also performance) than string concatenation.

🌐
Stack Overflow
stackoverflow.com › questions › 30640748 › string-and-int-concat-in-c
c++ - string and int concat in c - Stack Overflow
4 Concat strings and numbers in C++? 96 How to concatenate string and int in C? 0 String Concatenation with Integers · 3 concatenate char with int · 3 C - Concat Strings · 1 Arduino - Append int value to the end of a string for concatenated variables · 0 Concatenating an int to a string or converting in C ·
🌐
myCompiler
mycompiler.io › view › CbdSX7yud1I
concat integers (C) - myCompiler
November 5, 2022 - // C program to concatenate // two integers into one #include <stdio.h> #include <string.h> #include <stdlib.h> //imp // Function to concatenate // two integers into one int concat(int a, int b) { char s1[20]; char s2[20]; // Convert both the ...
Published: Oct 30, 2022
🌐
Quora
quora.com › In-C-is-there-anyway-to-concatenate-two-int-variables-E-g-If-a-1-and-b-0-I-want-ab-to-be-10
In C, is there anyway to concatenate two int variables? E.g. If a = 1 and b = 0, I want ab to be 10. - Quora
Answer (1 of 17): I feel this was inspired by my description of C preprocessor token pasting to OP the other day, given that it roughly references C preprocessor syntax. You can do this: [code]#include #define PASTE(x,y) x##y int main() { printf("%d\n", PASTE(1,0)); } [/code]That ...
🌐
Java2Blog
java2blog.com › concatenate-string-and-int-cpp
How to Concatenate String and Int in C++ – Java2Blog
One of the most straightforward ways in modern C++ (C++11 and later) is using the std::to_string() function. This function converts an integer into a string, making it easy to combine with other strings. How It Works: We include the <string> library. Convert the integer to a string using ...