[英]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.