[英]How to access the elements of a structure using variables with the exact name of the elements?
我不确定这是否至少是可能的,但我想使用具有元素确切名称的变量访问我的结构中的元素。
我的程序对结构的成员进行操作,它取决于用户选择的列,但为了使它更简单(因为这不是重点)我将写一些简单的行,所以它会是像这样:
(假设我已经用另一个函数填写了列表,但这也不是重点,所以我就不放了)
该结构将用于双向链表的每个节点(每个节点代表两列表中的一行)
typedef struct row {
float A, B;
struct row *prev, *next;
} _row;
主要的
int main(){
char column;
printf("Which column would you like to see? (A or B): ");
scanf("%c",&column);
show_column(column);
system("PAUSE");
}
和功能
void show_column(char column){
_row *aux;
aux=start;
while(aux->next!=NULL){
printf("\n %.2f",aux->column);
aux=aux->next;
}
//this is because that cycle is not going to show the last node
printf("\n %.2f",aux->column);
}
“开始”也是一个_row。 它被修改为在我插入节点的同一函数中指向列表的开始。
我想知道的是如何在函数中制作这部分:
printf("\n %.2f",aux->column);
因为“column”不是结构中的成员,而是一个变量,应该包含其中一个成员(A 或 B)的名称。
我需要这个,所以我不必重复相同的代码,而是使用“if”并且只用一个字母 (B) 不同。
对不起,如果拼写和语法有问题,我的英语不是很好,非常感谢您的帮助!
C 不是解释型语言,而是编译型语言。 据我所知这是不可能的。 您将不得不编写额外的代码。 此外,对于一个简单的用户来说,知道您的结构字段的名称并不好 - 所以,不要担心 =)。
所以基本上用户给你'A',你想要A列。
如果它只是单个字符的情况,那么您可以只使用字符后面的 int
使您的浮点数成为这样的数组:
typedef struct row {
float col[2]; //A, B
struct row *prev, *next;
} _row;
然后改变
printf("\n %.2f",aux->column);
成为
printf("\n %.2f",aux->col[(int(toUpper(column) - 'A'))]);
所以'A'将变为0,
'B' 将变为 1,依此类推。
这仅适用于单字符列名,所以如果你想要一个列“AA”,如果不做一些修改就行不通。
你可以这样做printf("\\n %.2f",(*(aux->column) == 'A' ? aux->A : aux->B));
除了 if 语句之外,我不知道您如何以其他方式执行此操作。
也许你可以这样做:
typedef struct row {
float col[2];
struct row *prev, *next;
} _row;
int main(){
char column;
printf("Which column would you like to see? (A or B): ");
scanf("%c",&column);
show_column(column);
system("PAUSE");
}
void show_column(char column){
_row *aux;
aux=start;
column = column - 'A';
while(aux->next!=NULL){
printf("\n %.2f",aux->col[column]);
aux=aux->next;
}
//this is because that cycle is not going to show the last node
printf("\n %.2f",aux->col[column]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.