C에서 int를 문자열로 변환하려면 어떻게 해야 합니까?
어떻게 변환합니까?int
줄에 맞춰?데이터 변환 기능을 만들려고 합니다.struct
문자열로 변환하여 파일에 저장합니다.
사용할 수 있습니다.sprintf
하기 위해서, 혹은 어쩌면snprintf
있는 경우:
char str[ENOUGH];
sprintf(str, "%d", 42);
여기서, 의 문자수(및 종단 문자)는str
는 다음 방법으로 계산할 수 있습니다.
(int)((ceil(log10(num))+1)*sizeof(char))
간단한 답변은 다음과 같습니다.
snprintf( str, size, "%d", x );
긴 것은, 우선 충분한 사이즈를 알아내는 것입니다. snprintf
를 사용하여 호출하면 길이를 알 수 있습니다.NULL, 0
첫 번째 파라미터로서:
snprintf( NULL, 0, "%d", x );
null-terminator에 1글자를 더 할당합니다.
#include <stdio.h>
#include <stdlib.h>
int x = -42;
int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);
가 모든 형식 문자열에서 작동하므로 를 사용하여 float 또는 double을 문자열로 변환할 수 있습니다."%g"
, int 를 16진수로 변환할 수 있습니다."%x"
기타 등등.
편집: 댓글에 지적된 바와 같이itoa()
표준이 아니므로 경쟁사의 답변에 제시된 sprintf() 접근방식을 사용하는 것이 좋습니다.
사용할 수 있습니다.itoa()
정수 값을 문자열로 변환하는 함수입니다.
다음은 예를 제시하겠습니다.
int num = 321;
char snum[5];
// convert 123 to string [buf]
itoa(num, snum, 10);
// print our string
printf("%s\n", snum);
구조를 파일로 출력하려면 미리 값을 변환할 필요가 없습니다.printf 형식 지정을 사용하여 값을 출력하는 방법을 지정하고 printf 패밀리의 연산자를 사용하여 데이터를 출력할 수 있습니다.
gcc용 itoa의 다양한 버전을 살펴본 결과, 바이너리, 10진수, 16진수로의 변환을 처리할 수 있는 가장 유연한 버전은 http://www.strudel.org.uk/itoa/에서 구할 수 있는 네 번째 버전입니다.하는 동안에sprintf
/snprintf
10진수 변환 이외에는 음수를 처리하지 않는다는 장점이 있습니다.위의 링크는 오프라인이거나 더 이상 활성화되지 않으므로 아래에 4번째 버전을 포함시켰습니다.
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
이것은 오래되었지만 다른 방법이 있다.
#include <stdio.h>
#define atoa(x) #x
int main(int argc, char *argv[])
{
char *string = atoa(1234567890);
printf("%s\n", string);
return 0;
}
임의의 것을 문자열로 변환하려면 1) 결과 문자열을 할당하거나 2) 전달해야 합니다.char *
대상 및 크기.아래 샘플 코드:
둘 다 모두에게 효과가 있다int
포함하여INT_MIN
. 이 명령어는 다른 명령어와 달리 일관된 출력을 제공합니다.snprintf()
현재 로케일에 따라 다릅니다.
방법 1: 반환NULL
메모리 부족에 대응하고 있습니다.
#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)
char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf] - 1;
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}
Method 2: 반환NULL
버퍼가 너무 작을 경우.
static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}
char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}
@Alter Mann의 요청에 따라 [편집]
(CHAR_BIT*sizeof(int_type)-1)*10/33+3
최소 최대 수char
부호 있는 정수 타입을 임의의 음수 기호, 숫자 및 늘 문자로 이루어진 문자열로 부호화하기 위해 필요합니다.
있는 는 '부호 비트 수'를 넘지 .CHAR_BIT*sizeof(int_type)-1
의 .n
- - "비트의 바이너리 수가 최대 - "비트의 바이너리 수: "비트의 바이너리 수"입니다.n*log10(2) + 1
디지트 10/33
많다log10(2)
기호 +1char
+1면 됩니다.28/93으로 하다
방법 3: 엣지에 살고 싶어도 버퍼 오버플로는 문제가 되지 않는 경우, 모든 것을 처리하는 간단한 C99 이후의 솔루션을 사용합니다. int
.
#include <limits.h>
#include <stdio.h>
static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}
char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}
int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}
출력 예시
0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648
GCC 를 사용하고 있는 경우는, GNU 확장 asprintf 함수를 사용할 수 있습니다.
char* str;
asprintf (&str, "%i", 12313);
free(str);
sprintf는 바이트를 반환하고 null 바이트도 추가합니다.
# include <stdio.h>
# include <string.h>
int main() {
char buf[ 1024];
int n = sprintf( buf, "%d", 2415);
printf( "%s %d\n", buf, n);
}
출력:
2415 4
구조를 파일로 출력하려면 미리 값을 변환할 필요가 없습니다.printf 형식 지정을 사용하여 값을 출력하는 방법을 지정하고 printf 패밀리의 연산자를 사용하여 데이터를 출력할 수 있습니다.
/*Function return size of string and convert signed *
*integer to ascii value and store them in array of *
*character with NULL at the end of the array */
int itoa(int value,char *ptr)
{
int count=0,temp;
if(ptr==NULL)
return 0;
if(value==0)
{
*ptr='0';
return 1;
}
if(value<0)
{
value*=(-1);
*ptr++='-';
count++;
}
for(temp=value;temp>0;temp/=10,ptr++);
*ptr='\0';
for(temp=value;temp>0;temp/=10)
{
*--ptr=temp%10+'0';
count++;
}
return count;
}
사용itoa()
정수를 문자열로 변환하다
예를 들어 다음과 같습니다.
char msg[30];
int num = 10;
itoa(num,msg,10);
언급URL : https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c
'programing' 카테고리의 다른 글
글로벌 변수와 스태틱 변수가 기본값으로 초기화되는 이유는 무엇입니까? (0) | 2022.07.14 |
---|---|
VUE 감시가 무한 루프를 트리거했습니다. (0) | 2022.07.05 |
동적 할당 없이 실행 시 어레이 크기가 허용됩니까? (0) | 2022.07.05 |
vue getter를 사용하여 개체 내부의 값을 찾는 방법은 무엇입니까? (0) | 2022.07.05 |
서명된 int와 서명되지 않은 int의 차이점은 무엇입니까? (0) | 2022.07.05 |