내 구조체 값을 내 인쇄 함수에 전달한 다음 main에서 호출하는 방법은 무엇입니까? -C 언어

멍청한 놈

이것은 아래 내 코드입니다.

enum DifficultyKind 
{
    Normal,
    Hard,
    Insane
} DifficultyKind;

typedef struct Target_Data
{
    my_string name;
    int  hit_id;
    int dollarvalue;
    enum DifficultyKind difficulty;
} Target_Data;

enum DifficultyKind read_difficulty_kind (const char *prompt)
{
int temp;

enum DifficultyKind result;
printf("%s\n", prompt);

printf("\n");
printf("1: Normal Difficulty \n");
printf("\n");
printf("2: Hard Difficulty \n");
printf("\n");
printf("3: Insane Difficulty \n");
printf("\n");

temp = read_integer("Please make a selection between 1 and 3: \n");
if (temp < 1) {
    printf("\n");
    printf("You did not make a selection between 1 and 3\n");
    printf("\n");
    temp = read_integer("Please make a selection between 1 and 3: \n");
}

if (temp > 3) {
    printf("\n");
    printf("You did not make a selection between 1 and 3\n");
    printf("\n");
    temp = read_integer("Please make a selection between 1 and 3: \n");
}

result = temp - 1;
return result;
}

Target_Data read_target_data (const char *prompt)
{
Target_Data result;
enum DifficultyKind Difficulty;
printf("%s\n", prompt); 

result.name = read_string("Enter name: ");

result.hit_id = read_integer("Enter hit ID: ");
if (result.hit_id < 0) {
    printf("Please enter a value of 0 or higher \n");
    result.hit_id = read_integer("Enter hit ID: ");
}

result.dollarvalue = read_integer("Enter $ value of target: ");
if (result.dollarvalue < 0) {
    printf("Please enter a value of 0 or higher \n");
    result.dollarvalue = read_integer("Enter $ value of target: ");
}

Difficulty = read_difficulty_kind("Please select the level of difficulty this bounty is from the below options:");

return result;
}

void print_target_data (Target_Data *toPrintData)
{
    printf("\nDifficulty: %d, Target: %s, Hit ID: %i, $%i,\n", toPrintData->difficulty, toPrintData->name.str, toPrintData->hit_id, toPrintData->dollarvalue);
}

int main() 
{
    Target_Data *Target_Data;
    read_target_data("Please enter the details of your bounty: ");
    print_target_data(&Target_Data);
}

프로그램이 실행되고 세부 정보를 입력하면 다음과 같이 표시됩니다.

Please enter the details of your bounty: 
Enter name: Jonathan
Enter hit ID: 10
Enter $ value of target: 500
Please select the level of difficulty this bounty is from the below options:

1: Normal Difficulty 

2: Hard Difficulty 

3: Insane Difficulty 

Please make a selection between 1 and 3: 
1

Difficulty: 10, Target: , Hit ID: 0, $0,

나는 너무 많은 다른 방법을 시도하고 해결책을 찾아 보았지만 실제로 무엇을 해야할지 모르겠습니다.

난이도가 히트 ID로 입력 한 숫자로 표시되고 나머지 세부 정보도 표시되지 않는 이유는 무엇입니까?

이것은 또한 내가 컴파일 할 때받는 경고 메시지입니다.

BountyHunter.c:96:20: warning: incompatible pointer types passing
  'Target_Data **' (aka 'struct Target_Data **') to parameter of type
  'Target_Data *' (aka 'struct Target_Data *'); remove &
  [-Wincompatible-pointer-types]
    print_target_data(&Target_Data);
                      ^~~~~~~~~~~~
BountyHunter.c:87:38: note: passing argument to parameter 'toPrintData' here
void print_target_data (Target_Data *toPrintData)

누군가 도와주세요!

데이비드 C. 랭킨

코드에 엄청난 수의 오류가있어 읽기를 검증하는 데 필요한 모든 코드가 부족하여 식별하기가 훨씬 더 어려워졌습니다. 즉, 또는 (현재 학습을 지나치게 복잡하게 만들 수 있는) 구조체를 동적으로 선언 할 필요 Target_Data가없는 주소로 전달되는 정적으로 선언 예제를 사용하도록 예제를 다시 작성 했습니다.read_target_dataread_target_dataread_difficulty_kind

나는 당신이 자바에서 왔는지 또는 자바 코드를 복사하려고 시도했는지 toPrintData->name.str모르지만 전혀 의미가 없습니다.

또한 코드 내에서 반환 된 값의 유효성을 검사 할 수 있도록 추가 err = -1했습니다 DifficultyKind enum. 수행 방법은 사용자에게 달려 있지만 실제로 실제 값으로 작업하고 초기화되지 않은 값을 처리하지 않으려면 각 입력의 유효성검사 해야 합니다.

(부수적으로 C는 일반적으로 소문자 변수 이름 camelCaseUpperCase사용하고 Java 및 C ++에 대한 이름 이름을 남기고 UPPERCASE매크로 등의 이름을 예약 합니다. 물론 스타일이므로 전적으로 귀하에게 달려 있습니다)

그 말로, 여기에 내가 당신의 의도와 함께 유지한다고 믿는 재 작업 된 예가 있습니다. 자세히 살펴보고 더 궁금한 점이 있으면 알려주세요. 입력 루틴은 단순히에 대한 호출입니다 scanf( fgets다음에 대한 호출에 대한 호출이 더 적절해야 sscanf하지만 다른 날에 대한 것임 ).

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

#define MAXC 128

typedef enum { err = -1, Normal = 1, Hard, Insane } DifficultyKind;

typedef struct {
    char name[MAXC];
    int hit_id;
    int dollarvalue;
    DifficultyKind difficulty;
} Target_Data;

DifficultyKind read_difficulty_kind (const char *prompt)
{
    int rtn, temp;

    printf ("%s\n\n"
            " 1: Normal Difficulty\n"
            " 2: Hard Difficulty\n"
            " 3: Insane Difficulty\n\n", prompt);

    while ((rtn = scanf (" %d", &temp)) != 1 || (temp < 1 || temp > 3)) {
        if (rtn == EOF)
            return err;  /* trap cancel of input (ctrl+d, ctrl+z) */
        fprintf (stderr, "error: invalid selection\n"
                        "Please make a selection between 1 and 3:\n\n"
                        " 1: Normal Difficulty\n"
                        " 2: Hard Difficulty\n"
                        " 3: Insane Difficulty\n\n");
    }

    return temp;
}

Target_Data *read_target_data (Target_Data *result, const char *prompt)
{
    int rtn;

    printf ("%s\n\nEnter name: ", prompt);
    while ((rtn = scanf (" %127[^\n]%*c", result->name) != 1))
        if (rtn == EOF) {
            fprintf (stderr, "warning: input canceled, exiting.\n");
            exit (EXIT_FAILURE);
        }

    printf ("Enter hit ID: ");
    while ((rtn = scanf (" %d", &(result->hit_id)) != 1) ||
            result->hit_id < 0) {
        if (rtn == EOF) {
            fprintf (stderr, "warning: input canceled, exiting.\n");
            exit (EXIT_FAILURE);
        }
        fprintf (stderr, "Please enter a value of 0 or higher \n");
        printf ("Enter hit ID: ");
    }

    printf ("Enter $ value of target: ");
    while ((rtn = scanf (" %d", &(result->dollarvalue)) != 1) || 
            result->dollarvalue < 0) {
        if (rtn == EOF) {
            fprintf (stderr, "warning: input canceled, exiting.\n");
            exit (EXIT_FAILURE);
        }
        fprintf (stderr, "Please enter a value of 0 or higher \n");
        printf ("Enter $ value of target: ");
    }

    if ((result->difficulty = read_difficulty_kind ("Please select the"
            " level of difficulty from the options below:")) == err) {
        fprintf (stderr, "warning: input canceled, exiting.\n");
        exit (EXIT_FAILURE);
    }

    return result;
}

void print_target_data (Target_Data *toPrintData)
{
    printf ("\nDifficulty: %d, Target: %s, Hit ID: %i, $%i,\n",
            toPrintData->difficulty, toPrintData->name,
            toPrintData->hit_id, toPrintData->dollarvalue);
}

int main (void) {

    Target_Data Target_Data = { .name = "" };
    read_target_data (&Target_Data, 
                    "Please enter the details of your bounty: ");
    print_target_data (&Target_Data);

    return 0;
}

사용 / 출력 예시

$ ./bin/difficultystruct
Please enter the details of your bounty:

Enter name: Some Funny Name
Enter hit ID: 123
Enter $ value of target: 234
Please select the level of difficulty from the options below:

 1: Normal Difficulty
 2: Hard Difficulty
 3: Insane Difficulty

0
error: invalid selection
Please make a selection between 1 and 3:

 1: Normal Difficulty
 2: Hard Difficulty
 3: Insane Difficulty

4
error: invalid selection
Please make a selection between 1 and 3:

 1: Normal Difficulty
 2: Hard Difficulty
 3: Insane Difficulty

2

Difficulty: 2, Target: Some Funny Name, Hit ID: 123, $234,

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관