在C中操纵char数组后的随机符号 [英] Random symbols after manipulating a char array in C

查看:71
本文介绍了在C中操纵char数组后的随机符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void coma(char* str){
int j, i = 0;
int size = strlen(str);
int commas = (size-3)/3;
int left = (size-3)%3;
char tmp[20];

for(j = 0; j<size; i++){
    if(left || commas == 0){
        tmp[i] = str[j++];
        left--;
    }else {
        tmp[i] = ',';
        left = 3;
        commas--;
    }        
}
strcpy(str,tmp);    }

int main(){

char str[0x100];
float x = 5002052.1111;

sprintf(str,"%.2f", x);

coma(str);
printf("%s\n",str);  }

我正在尝试在浮点数的第三个位置插入逗号,例如数字 5002052.1111将会是 5,002,052.11
,但是当我运行程序而不是得到我期望的结果时,我会得到正确的答案以及诸如 5,002,052.11 @ {

I am trying to insert commas every third place on a float number for example the number "5002052.1111" will be "5,002,052.11" but when I run the program instead of getting what I am expecting I get the correct answer plus random symbols like "5,002,052.11@ {"

我注意到,如果将确切的数字大小放在char tmp []中,它将可以正常工作,但是我需要它可以处理任何大小的数字。

I notice that if I put the exact size of number in the char tmp[] it will work fine, but I need it to work with any size of numbers.

我正在使用gcc。

推荐答案

'\0'附加到 tmp 字符串,然后调用 strcpy()

append '\0' to the tmp string, before calling strcpy()

这篇关于在C中操纵char数组后的随机符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆