在c

时间:2016-11-07 17:48:34

标签: c

我希望有人能告诉我如何在c中打印出带有对象的数组。

这是我的代码:

typedef struct{
    int user_id;
    char username[100];
    char password[100];
    int ano_nascimento;
} Utilizador;

int main(){
    Utilizador lista[50];
    FILE *fb = fopen("utilizadores.dat","a");
    int i=0;
    Utilizador a; 
    while( fread(&a,sizeof(a),1,fb) > 0 )
            lista[i++]=a;

    int n;
    printf("\nMenu\n\n1 - Criar Novo Utilizador\n2 - Listar Utilizadores\n3 - Apagar Utilizador\n0 - Sair\n\n");
    scanf("%d",&n);
    switch(n){
            case 1: a = introduzir_utilizador();
                    fwrite (&a,sizeof(a),1,fb);
                    fclose(fb); 
                    break;
            case 2:for(int i=0; i!=sizeof(lista); i++){
                            printf("%d %s %s %d",lista[i].user_id,lista[i].username, lista[i].password, lista[i].ano_nascimento);
                            printf("\n");
                    }
            case 3:;
            case 4:;
            case 0:;
            default: ;
    }

}

这里的问题是打印名为" lista"哪个有" utilizadores"在其中

1 个答案:

答案 0 :(得分:1)

问题在于,您没有记录有多少“使用者”。你在攒钱。试试这个:

% windowSize assumed to be odd; window assumed to be square
windowSize = 3;

% pad the input image
% padsize is how far the window extends beyond anchor
padsize = floor(windowSize/2);
A = padarray(I, [padsize, padsize], nan);

% create an anonymous function for nlfilter to use
% calculate row/column number of anchor within its neighborhood
anchor = ceil(windowSize/2);
% subtract the anchor element from its neighbors
%   then sum the neighbors *not* equal to NaN
%   (value at anchor position will be 0)
f = @(x) sum(nansum(abs(x-x(anchor,anchor))));

% filter padded image, and then crop off the padding
del = nlfilter(A, [windowSize, windowSize], f);
del = del(1+padsize:end-padsize, 1+padsize:end-padsize);

int records = 0; // we need this to keep track of how many records we have

case 1:
    a = introduzir_utilizador();
    fwrite(&a, sizeof(a), 1, fb);
    fclose(fb);
    records++; // we have one more record
    break;

通过这样做,您只会显示' lista'的有效元素。

同样的:

case 2:
    // go though until the number of records has reached
    for(int i = 0; i != records; i++)
    {
        printf("%d %s %s %d",
               lista[i].user_id,
               lista[i].username,
               lista[i].password,
               lista[i].ano_nascimento);
        printf("\n");
    }

跟踪有多少' utilizadores'您已阅读并将其添加到记录变量中:

while (fread(&a, sizeof(a), 1, fb) > 0)
    lista[i++] = a;

顺便说一句,我可以看到您打算删除' utilizadores'。 请记住减少'记录的数量。