在 sprintf 函数中添加逗号
Add comma in a sprintf function
>我在看主题:如何在 C 中将数字从 1123456789 格式化为 1,123,456,789?
所以我基于现有的代码挂载了我的代码。
void printfcomma(char *buf, const char* text int n) {
if (n < 1000) {
sprintf(buf, "%s %d", text, n);
return;
}
printfcomma(buf, n / 1000);
sprintf(buf, "%s ,%03d", text, n %1000);
return;
}
Sprintf 只返回最后 3 位数字。示例:,536
有谁知道为什么他们不显示其他数字
您正在覆盖。
你应该做sprintf(s+ strlen(s),"abcde");
void printfcomma(char *buf,int n) {
if (n < 1000) {
sprintf(buf+strlen(buf), "%d", n);
return;
}
printfcomma(buf, n / 1000);
sprintf(buf+strlen(buf), ",%03d", n %1000);
return;
}
在调用函数中
memset(s,0,sizeof(s));// s is the char array.
printfcomma(s,100000536);
输出
100,000,536
正如@coderredoc所回答的那样,代码正在覆盖buf
。
调用 strlen()
的替代方法是利用 sprintf()
的返回值。
sprintf
函数返回数组中写入的字符数,不计算终止 null 字符,如果发生编码错误,则返回负值。 C11dr §7.21.6.6 3
进一步:代码也应该处理负数。
const char* text
用途尚不清楚。 下面的示例代码不使用它。
int printfcomma(char *buf, int n) {
if (n > -1000 && n < 1000) { // avoid (abs(n) < 1000) here. abs(INT_MIN) is a problem
return sprintf(buf, "%d", n);
}
int len = printfcomma(buf, n / 1000);
if (len > 0) {
len += sprintf(buf + len, ",%03d", text, abs(n % 1000)); // do not print `-`
}
return len;
}
用法
char s[sizeof(int)*CHAR_BIT]; // Somehow, insure buffer size is sufficient.
printfcomma(s, INT_MIN);
puts(s); --> -2,147,483,648
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- sprintf() 正在添加一个额外的变量
- 如何使用sprintf将UINT_64的数组添加到一个字符数组中
- 在 sprintf 函数中添加逗号