将返回值分配给Struct(C ++)

时间:2014-06-28 18:16:09

标签: c++ struct

我对C ++很新,我只是在学习结构和枚举。我决定将它们付诸实践,在制作了一个简单的程序来读取有关宠物的不同信息的用户输入后,我遇到了一个错误。每当我运行我的程序时,它会获得用户输入,当它打印出来时,它只是打印" 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;

}

1 个答案:

答案 0 :(得分:3)

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

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

system("PAUSE");
相关问题