Table of Contents
ToggleWhat Does C++ Int to String Mean?
In C++, int to string means converting a number (int) into text (string) so it can be used easily in output, display, or formatting.
int = number
string = text
So,
int → string
Example:
int a = 10;
string s = “10”;
The value is same, but data type is changed.
This process is called C++ int to string conversion.
Why We Use Int to String in C++?
We convert int to string when:
- We want better output formatting
- We need to add zeros before numbers
- We work with Arduino
- We combine numbers with text
- We display numbers on screen
Method 1: C++ Int to String Using to_string() (Best Method)
#include
#include
using namespace std;
int main() {
int num = 25;
string s = to_string(num);
cout << s;
return 0;
}
Explanation
num = 25
s = “25”
✔ Easy
✔ Beginner friendly
✔ Most used method
Method 2: C++ Int to String Using stringstream
#include
#include
using namespace std;
int main() {
int num = 40;
string s;
stringstream ss;
ss << num;
s = ss.str();
cout << s;
return 0;
}
Why Use This Method?
- Works in old C++ (C++98)
- Safe for exams
- Very reliable
C++ Int to String with Leading Zeros
Sometimes we need output like:
005
010
099
Example Code
#include
#include
#include
using namespace std;
int main() {
int num = 5;
stringstream ss;
ss << setw(3) << setfill('0') << num;
string result = ss.str();
cout << result;
return 0;
}
Output
005
C++ Int to String Zero Padding
Zero padding means:
number = 7
string = “007”
Used in:
- Roll numbers
- IDs
- Timers
- Counters
C++ Int to String Hex Conversion
//Convert integer into hexadecimal string:
#include
#include
using namespace std;
int main() {
int num = 255;
stringstream ss;
ss << hex << num;
string s = ss.str();
cout << s;
return 0;
}
// COMMENTS
// Output
//ff
C++ Int to String in Arduino
Arduino Method
int num = 100;
String s = String(num);
C-Style Arduino Method
int num = 100;
char buffer[10];
itoa(num, buffer, 10);
C++ Int to Char (Single Digit Only)
int num = 7;
char ch = num + ‘0’;
7 → ‘7’
⚠ Works only for 0–9
Int to String C (Not C++)
C language uses character arrays.
#include
int main() {
int num = 30;
char str[10];
sprintf(str, "%d", num);
printf("%s", str);
return 0;
}
Int to String C++98 (Old Standard)
Before to_string():
#include
using namespace std;
int num = 20;
stringstream ss;
ss << num;
string s = ss.str();
✔ C++98 compatible
✔ Exam safe
Recommended : How to Use GDB to Debug a C++ Program
How to Convert String to Int in C++ Without stoi
#include
using namespace std;
string s = "123";
int num;
stringstream ss(s);
ss >> num;
FAQs – C++ Int to String
What is the easiest way to convert int to string in C++?
Use to_string().
How to add leading zeros in C++ int to string?
Use setw() and setfill().
Does to_string() work in old C++?
No, it needs C++11 or later.
How to convert int to string in Arduino?
Use String(num) or itoa().
How to convert string to int without stoi?
Use stringstream.