从存储枚举的vector中取出元素时如何获取原始输入值?
问题解决:从vector中获取原始输入值而非数字
问题描述
从用户处获取输入并存入vector后,取指定索引值时得到的是数字(比如输出79),而非原始输入的字符。代码示例如下:
enum Enums { I, O,T, J , L, S, Z }; int main() { unsigned int index; Piece piece; for (index=0; index < 5; index ++) { cout << "What are the " << index+1 << ". piece?\n"; cin >> piece.inputPiece; piece.pieceList.push_back(static_cast<Enums>(piece.inputPiece)); } Enums firstPiece= piece.pieceList[0]; cout <<firstPiece; }
原因分析
- 你输入的是字符(比如
'O'),它的ASCII码值是79,直接用static_cast<Enums>(piece.inputPiece)会把ASCII码数值强转成枚举类型存储,而非对应枚举项O的默认值1。 - 用
cout输出枚举变量时,默认会把它当作整数输出,所以你看到的是79这个ASCII码值,而不是原始输入的字符。
解决方案
方案1:同时存储原始输入字符
如果需要保留原始输入,直接在Piece类里新增一个存储字符的vector,把输入的字符直接存进去:
#include <iostream> #include <vector> using namespace std; enum Enums { I, O,T, J , L, S, Z }; struct Piece { char inputPiece; vector<Enums> pieceList; vector<char> originalInputs; // 新增存储原始输入的容器 }; int main() { unsigned int index; Piece piece; for (index=0; index < 5; index ++) { cout << "What are the " << index+1 << ". piece?\n"; cin >> piece.inputPiece; piece.originalInputs.push_back(piece.inputPiece); // 保存原始输入字符 // 可选:将输入字符正确映射到枚举项 switch(piece.inputPiece) { case 'I': piece.pieceList.push_back(I); break; case 'O': piece.pieceList.push_back(O); break; case 'T': piece.pieceList.push_back(T); break; case 'J': piece.pieceList.push_back(J); break; case 'L': piece.pieceList.push_back(L); break; case 'S': piece.pieceList.push_back(S); break; case 'Z': piece.pieceList.push_back(Z); break; default: cout << "无效输入,请重新输入" << endl; index--; // 回退索引,重新输入当前项 break; } } // 直接获取并输出原始输入值 cout << "第一个原始输入:" << piece.originalInputs[0] << endl; }
方案2:建立枚举与字符的映射表
如果只存储枚举值,可通过映射表将枚举值转回对应的字符:
#include <iostream> #include <vector> #include <unordered_map> using namespace std; enum Enums { I, O,T, J , L, S, Z }; // 枚举到字符的映射表 unordered_map<Enums, char> enumToChar = { {I, 'I'}, {O, 'O'}, {T, 'T'}, {J, 'J'}, {L, 'L'}, {S, 'S'}, {Z, 'Z'} }; // 字符到枚举的映射表 unordered_map<char, Enums> charToEnum = { {'I', I}, {'O', O}, {'T', T}, {'J', J}, {'L', L}, {'S', S}, {'Z', Z} }; struct Piece { char inputPiece; vector<Enums> pieceList; }; int main() { unsigned int index; Piece piece; for (index=0; index < 5; index ++) { cout << "What are the " << index+1 << ". piece?\n"; cin >> piece.inputPiece; // 通过映射表将输入字符转为正确的枚举值 auto it = charToEnum.find(piece.inputPiece); if(it != charToEnum.end()) { piece.pieceList.push_back(it->second); } else { cout << "无效输入,请重新输入" << endl; index--; } } Enums firstPiece = piece.pieceList[0]; // 通过映射表将枚举值转回原始字符输出 cout << "对应的原始输入字符:" << enumToChar[firstPiece] << endl; }
内容的提问来源于stack exchange,提问作者mordeby
相关产品推荐
相关产品推荐

