将返回值赋给结构体(c++)
Assigning Return Values to a Struct (C++)
我对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");
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 创建结构体向量,表达式:向量下标超出范围
- boost::任何带有结构体和无符号整数
- 如何在构造函数中初始化结构体的动态数组?
- 只写结构体的某些字段
- C++ push_back() 一个结构体到一个向量中
- C++14 结构体上的统一初始化
- 访问不同类的私有结构体成员