strcpy和strcmp的错误以及printf和scanf的参数[关闭]

问题描述 投票:-4回答:1
typedef struct staff {

int id, salary;
char name[30], position[30];
}staff;

void modifyStaff() {
char ans, cont, name[25], position[20];
int i = 0, pCount, modiCount = 0, found, id[20];
int salary[20];
staff P[20];
FILE*fp;
fp = fopen("staff.dat", "rb");
while (fread(&P[i], sizeof(staff), 1, fp))
    i++;
pCount = i;
fclose(fp);
do {
    printf("\nEnter ID of the Staff to be modified : ");

    rewind(stdin);
    scanf("%d", &id);
    found = 0;

    printf("\nID    NAME   POSITION    SALARY \n");
    printf("============   ===========    ======= \n");
    for (i = 0; i < pCount; i++) {
        if (id == P[i].id == 0) {
            found = 1;
            printf("%-18d %-10s %-10s %-10d \n",
                P[i].id, P[i].name, P[i].position, P[i].salary);
            printf("\n Updated Name:");

            scanf("%[^\n]", &name);
            printf("\n Updated Position:");

            scanf("%[^\n]", &position);
            printf("\n Updated salary:");

            scanf("%d", &salary);
            printf("Confirm to Modify (Y=yes)? ");

            scanf("%c", &ans);
            if (toupper(ans) == 'Y') {
                P[i].id = id;
                strcpy(P[i].name, name);
                strcpy(P[i].position, position);
                P[i].salary=salary;
                modiCount++;
            }
            printf("Updated Staff Records:\n");
            printf("\nID NAME POSITION SALARY\n");
            printf("========  ========= =========== ========\n");
            printf("%-18d %-10s %-10s %-10d", P[i].id, P[i].name, P[i].position, P[i].salary);
        }
    }
    if (!found)
        printf("NO record founded with this ID");
    printf("Any more record to modify?(Y=yes)?");

    scanf("%c", &cont);
} while (toupper(cont) == 'Y');
fp = fopen("staff.dat", "wb");
for (i = 0; i < pCount; i++)
    fwrite(&P[i], sizeof(staff), 1, fp);
fclose(fp);
printf("\n\t%d Record(s) modified.\n\n", modiCount);

}

它会改变名称和职位,但对于工资,它将显示违规行为。我想改变工资并存储新的工资。但它不能存储编译器执行的新工作,直到线路确认要修改?然后停止执行。谱表P表示修改函数中的所有P [i]

c
1个回答
1
投票

就像我在评论中所说:

  • strcpy()strncpy()函数返回指向目标字符串dest的指针。
  • 如果发现s1(或其前n个字节)分别小于,匹配或大于s2,则strcmp()strncmp()函数返回小于,等于或大于零的整数。

以下程序应解释两种功能的使用:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 256
struct pers{
    char dest[SIZE];
};

int main ( void ){

    struct pers data;
    const char *src = "Hello";

    if ( ( strlen( src ) + 1) <  SIZE ){
        strcpy( data.dest, src );
    }else{
        printf("The SRC is bigger then DEST\n");
        exit(EXIT_FAILURE);
    }

    if ( strcmp( data.dest, src ) == 0 ){
        printf("SRC and DEST are equal:\n\n");
        printf("\tSRC  = %s\n", src);
        printf("\tDEST = %s\n", data.dest);
    }else{
        printf("SRC and DEST are  NOT equal\n");
    }
}

输出:

SRC and DEST are equal:

    SRC  = Hello
    DEST = Hello
© www.soinside.com 2019 - 2024. All rights reserved.