0

我有以下部分代码:

         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]);
}
4

3 回答 3

2

假设您已经将您的价值观转化为“机器、数字、hr、dw、vcc”(谁是char*

您不能将它们存储到您的 char table1[1][10] 中,因为它是一个数组表,只能包含一个 10 个字符的数组。

所以你需要一个 char ** 看起来像:

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");

但是在您的情况下,为什么不简单地使用 int[10] ?

于 2013-06-20T12:21:14.937 回答
0

目前尚不清楚您到底想要什么,但只是试一试

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-20T12:20:01.643 回答
0

鉴于您能够操纵第一段代码,一种可能的方法是:

   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()值放入数组中。

于 2013-06-20T12:20:59.910 回答