我有以下部分代码:
i = 0;
while (ptr != NULL)
{
if (i == 0)
strcat(machine, ptr);
if (i == 2)
strcat(number, ptr);
if (i == 4)
strcat(hr, ptr);
if (i == 6)
strcat(dw, ptr);
if (i == 8)
strcat(vcc, ptr);
i++;
}
printf("Final: %s, %s, %s, %s, %s\n", machine, number, hr, dw, vcc);我得到的结果是:
Final: 3, 34, 56, 67, 56如何将它们保存在位置5-9的10位数组中?就像这样:
0 0 0 0 0 3 34 56 67 56我写了以下代码,但它没有完成,因为我不知道如何在表中传递&machine,&number,&hr,&dw,&vcc
FILE *ft = fopen("Desktop/mytext.txt","a+");
struct tm *tp;
time_t t;
char s[80];
t = time(NULL);
tp = localtime(&t);
strftime(s, 80, "%d/%m/%Y %H:%M:%S", tp);
char table1[1][10];
for(int i = 0; i<1; i++)
{
fprintf(ft,"%s ",s);
for(int j = 0; j<10; j++)
fprintf(ft,"%d ",table1[i][j]);
}发布于 2013-06-20 20:21:15
假设您已经将值输入到"machine,number,hr,dw,vcc“(who are char*)中
您不能将它们存储到char table11中,因为它是一个数组表,它只能包含一个10个字符的数组。
因此,您需要一个字符**,如下所示:
char *table1[10] = {0};
table1[5] = machine;
table1[6] = number;
table1[7] = hr;
table1[8] = dw;
table1[9] = vcc;但是要显示它,你会遇到一些问题,但你总是可以这样做:
for (int i = 0; i < 10; i++)
{
if (table1[i] == NULL)
printf("0 ");
else
printf("%s ", table1[i]);
}
printf("\n");但在您的情况下,为什么不简单地使用int10?
发布于 2013-06-20 20:20:02
还不清楚你到底想要什么,只是试一试。
char table1[1][10]={0};
table1[0][5]= machine;
table1[0][6]=number;
table1[0][7]=hr;
table1[0][8]=dw;
table1[0][9]=vcc;发布于 2013-06-20 20:21:00
假设您能够操作第一段代码,一种可能的方法是:
i = 0;
int offset = 5;
char* table[1][10];
while (ptr != NULL)
{
if (i == 0)
strcat(machine, ptr);
if (i == 2)
strcat(number, ptr);
if (i == 4)
strcat(hr, ptr);
if (i == 6)
strcat(dw, ptr);
if (i == 8)
strcat(vcc, ptr);
table[0][5+(i/2)] = ptr;
i++;
}
printf("Final: %s, %s, %s, %s, %s\n", machine, number, hr, dw, vcc);在第二段代码中,我将去掉外部的for循环,只需编写:
for(int j = 0; j<10; j++)
fprintf(ft,"%d ",table1[0][j]); 假设您确实只有一个这样的数组,正如您的声明所暗示的那样。
请注意,上面的解决方案只能在函数内部局部工作,因为返回局部变量不起作用。为了能够全局使用表结构,您可能希望将值malloc()和strcpy()放入数组中。
https://stackoverflow.com/questions/17213199
复制相似问题