Convert a number to a string with specified length in C++
or using the stringstreams:
#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::setw(10) << std::setfill('0') << i;
std::string s = ss.str();
I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.
How can I convert an int to a string in C?
As pointed out in a comment, itoa()
is not a standard, so better use the sprintf() approach suggested in the rival answer!
You can use the itoa()
function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// Convert 123 to string [buf]
itoa(num, snum, 10);
// Print our string
printf("%s\n", snum);
If you want to output your structure into a file there isn't any need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
How to convert integer to string in C?
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
int To String Representation of Fixed Length
You can use std::ostringstream
and treat it like an output stream:
std::ostringstream ss;
ss << std::setw( 4 ) << std::setfill( '0' ) << number;
Send_To_Serial(ss.str().c_str());
Convert int n into string of length n in C
#include <stdio.h>
#include <stdlib.h>
void number_to_alphabet_string(int n){
char buffer[n];
for(int i=0;i<n;i++){
buffer[i] = n + 64;
//check ASCII table the difference is fixed to 64
printf("%c",buffer[i]);
}
printf("\n");}
int main(void){
int C = 3;
number_to_alphabet_string(C);
int J = 10;
number_to_alphabet_string(J);
return 0;
}
If you are new to a low level programming language like C and you care about it then I strongly suggest you to go through a textbook and learn it from scratch rather than combining snipets of code. In general try to keep it simple and for tasks like that don't use complex syntax and data structures, c gives you low level control of types and that's something that you need to master if you perhaps need to use it further in the future.
Convert an integer to a fixed-length character array in C++
// Assume x is in the correct range (0 <= x <= 9999)
char target[5];
sprintf(target, "%04d", x);
Converting int to string in C
Use snprintf
, it is more portable than itoa
.
itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.
Example of sprintf
char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);
Example of snprintf
char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);
Both functions are similar to fprintf
, but output is written into an array rather than to a stream. The difference between sprintf
and snprintf
is that snprintf
guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer
.
strtod with limited string length
If you always want to only consider the three first characters from a given string, you can use the following code:
#include <stdio.h>
#include <string.h>
double parse_double(const char *str) {
char *tmp = 0;
double result = 0;
asprintf(&tmp, "%.3s", str);
result = strtod(tmp, 0);
free(tmp);
return result;
}
int main(void) {
printf("%f\n", parse_double("1.23")); // 1.2
printf("%f\n", parse_double("1234")); // 123
printf("%f\n", parse_double("0.09")); // 0.0
return 0;
}
Related Topics
Getting the Current Time (In Milliseconds) from the System Clock in Windows
Getting a Bunch of Crosses Initialization Error
Getting Std::Thread/Mutex to Work Under Win7 with Mingw and G++ 4.7.2
Implementing Component System from Unity in C++
Eigen How to Concatenate Matrix Along a Specific Dimension
Llvm Get Constant Integer Back from Value*
How to Create a Type List (For Variadic Templates) That Contains N-Times the Same Type
Compile Program for 32Bit on 64Bit Linux Os Causes Fatal Error
How to Overload a Function That Can Tell a Fixed Array from a Pointer
C++ Reading Unsigned Char from File Stream
G++ Error:/Usr/Lib/Rpm/Redhat/Redhat-Hardened-Cc1: No Such File or Directory
C++ Specialization of Template Function Inside Template Class
Opencv Image Loading for Opengl Texture
Why Copy Constructor Is Called When Passing Temporary by Const Reference
How to Use Cmake_Export_Compile_Commands
Visual Studio 2013 Error Ms8020 Build Tools V140 Cannot Be Found