下面是我的代码。我想使它更有效率。有这么多的格式说明它们是相同的。而且还有与数组属于类似的目标。
我的问题是...
谢谢你的帮助。
char * msg = sprintf("%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
intnum, doublenum[0], doublenum[1],
doublenum[2], doublenum[3], doublenum[4],
doublenum[5], doublenum[6], doublenum[7],
doublenum[8], doublenum[9], doublenum[10]);
首先,您需要提供足够大的缓冲区写入。 sprintf
的签名
int sprintf(char *str, const char *format, ...);
它返回写入缓冲区str
字符的数量。
您可以捕获该值由迄今写入的字符的偏移量的指针调整到str
。
没有任何错误检查和缓冲区溢出保护,它可能是这个样子:
char msg[BUFSZ];
int msgl = sprintf(msg, "%d", integer);
for(int i = 0; i < 10; ++i)
{
msgl += sprintf(msg + msgl, " %lf", ds[i]);
}
对于一些足够大BUFSZ
。
一个简单的example是: -
#include <stdio.h>
#include <string.h>
int main(void) {
char msg[100];
int x=1, i=0;
double d[10];
for(i=0; i<10; i++)
d[i] = i+10.0;
sprintf(msg, "%d", x);
for(i =0; i<10; i++){
sprintf(msg + strlen(msg), " %lf", d[i]);
}
printf("%s\n", msg);
return 0;
}
你最好的选择可能是沿着这些线路代码:
double array[10] = { 25.66, 87.51, 38.53, 26.59, 85.54, 47.82, 69.68, 27.79, 21.98, 12.80, };
enum { NUM_ARRAY = sizeof(array) / sizeof(array[0]) };
char buffer[1024];
int integer = 3141592;
int offset = 0;
int nbytes = snprintf(buffer + offset, sizeof(buffer) - offset, "%d", integer);
if (nbytes < 0) { …report error and stop processing… }
offset += nbytes;
for (int i = 0; i < NUM_ARRAY; i++)
{
nbytes = snprintf(buffer + offset, sizeof(buffer) - offset, " %lf", array[i]);
if (nbytes < 0) { …report error and stop processing… }
offset += nbytes;
}
严格地说,该代码应检查是否nbytes >= sizeof(buffer) - offset
,以确保没有截断。
不管你认为这是简单的又是另一回事。它是,但是,远远超过原来的弹性(或具有更灵活的潜力)。如果您需要打印仅8,或者打印一些大数量的值,然后(在功能适当的包装),你可以处理所有变体。你可以玩各种其他技巧,例如确保输出线不会比N个字节要长,插入新行,也许一些领先的填充。天空才是极限。
我写这个简单的示例代码读取命令行参数,并将它们插入到可变msg
。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char msg[2000];
int msgl;
int x,i,n;
double d[10];
// Load values from command line
// -----------------------------------------
if (argc>12 || argc<3) {
puts("Usage: prgname ni nd1 {nd2,nd3 ..., nd10}\n");
return 1;
}
n=argc-2; // number of double values
x=atoi(argv[1]);
for(i=0;i<n;i++)
d[i]=strtod(argv[i+2],NULL);
// -------------------------------------------
// -------------------------------------------
// THE ALGORITHM SOLVING THE QUESTION
// -------------------------------------------
*msg=0; // clear msg
msgl = sprintf(msg,"%d",x);
for(i=0;i<n;i++)
msgl += sprintf(msg + msgl," %lf", d[i]);
// -------------------------------------------
puts(msg);
return 0;
}