【问题标题】:assign a variable value to dynamic c array将变量值分配给动态 c 数组
【发布时间】:2020-07-27 00:19:33
【问题描述】:

您好,我想将我的计数值赋给这个 'ob' 结构体 'p_id' 变量。我怎样才能做到这一点?我从文件中读取了其他值,但我需要一个用于选择的 id,并且我使用 count 来进行选择。但我不知道如何评价它。

我的 .txt 文件;

0 0

0 1

1 1

FILE *fp;

struct ob{ 
   int x;
   int y;
   int p_id;
};
struct ob* ptr;
int count=0;


ptr = (struct ob*)malloc(sizeof(struct ob));
while(!feof(fp))
{
  ++count;
  fscanf (fp,"%d%d%d", &ptr->x, &ptr->y, &ptr->p_id=count); /* in here I want to assing count to p_id */
  printf("%d %d %d",ptr->x, ptr->y, ptr->p_id);
  
 }
  fclose (fp);
}

【问题讨论】:

  • 如果您想从文件中读取p_id 或用count 覆盖它,只需下定决心。如果您希望 fscanf 读取为“虚拟读取”,则只需在 fscanf 之后的一行上执行ptr->p_id = count;
  • 我的文件中没有任何 p_id。我需要在读取文件后添加它。如果我确实像我对问题所做的那样,代码编译器会给我一个错误(错误:需要左值作为赋值的左操作数)
  • 你能显示文件上下文的 sn-p 吗?
  • 如果文件中没有pid,你想用第三个%d读取什么?
  • @Gerhardh 谢谢我没注意到。

标签: c arrays variable-assignment


【解决方案1】:

如果您只是想为ptr->p_id 分配一个序列号,请将其从fscanf 调用中删除并在其后赋值:

 fscanf (fp,"%d%d", &ptr->x, &ptr->y);
 ptr->p_id=count;

如果您希望该值是可选的,您可以在调用之前移动分配,并让fscanf 覆盖它(如果存在):

 ptr->p_id=count;
 fscanf (fp,"%d%d%d", &ptr->x, &ptr->y, &ptr->p_id);

fscanf的返回值可以让你查看值是否更新:

RETURN VALUE
       On success, these functions return the number of input items
       successfully matched and assigned; this can be fewer than provided
       for, or even zero, in the event of an early matching failure.

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2015-12-14
    • 2021-12-05
    相关资源
    最近更新 更多