将返回值赋给结构体(c++)

Assigning Return Values to a Struct (C++)

本文关键字:c++ 结构体 返回值      更新时间:2023-10-16

我对c++相当陌生,我只是学习结构体和枚举。我决定把它们付诸实践,在编写了一个简单的程序来读取用户输入的关于宠物的不同信息后,我遇到了一个bug。每当我运行我的程序时,它得到用户输入,当它打印出来时,它只是打印"NAME:"我认为问题是我给结构体成员分配返回值。如果是这样,我该如何修复我的代码?

#include <iostream>
#include <string>
#include "ANIMALS.h"
animalType getType();
std::string getName();
int getAge();
int main(){
    yourPet userInput;
    userInput.yourPetsAge = getAge();
    userInput.yourPetsName = getName();
    userInput.yourPetsSpecies = getType();
    std::cout << "This is your pet's info: NAME: ", userInput.yourPetsName,
    " AGE: ", userInput.yourPetsAge, " SPECIES: ", userInput.yourPetsSpecies;
system("PAUSE");
return 0;
}
animalType getType(){
    int speciesChoice;
    std::cout << "What type of pet do you have?nEnter the corresponding number to        your  pet's species" << std::endl;
    std::cout << "1: DOG 2: CAT 3: FISH 4: BIRD" << std::endl;
    std::cin >> speciesChoice;
    if (speciesChoice == 1){
    return DOG;
    }
    if (speciesChoice == 2){
        return CAT;
    }
    if (speciesChoice == 3){
        return FISH;
    }
    if (speciesChoice == 4){
        return BIRD;
    }
}
std::string getName(){
    std::string petName;
    std::cout << "What is your pet's name?" << std::endl;
    std::cin >> petName;
    return petName;
}
int getAge(){
    int petAge;
    std::cout << "What is your pet's age?" << std::endl;
    std::cin >> petAge;
    return petAge;
}

使用<<分隔输出,而不是逗号:

std::cout << "This is your pet's info: NAME: " << userInput.yourPetsName <<
             " AGE: " << userInput.yourPetsAge << 
             " SPECIES: " << userInput.yourPetsSpecies;
system("PAUSE");