C++ store number in char using int variable
我需要能够使用变量将数字存储在char中,并且稍后能够检测出它是用于打印的数字还是字符,将尝试使用以下代码示例进行解释:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <vector> using namespace std; int main() { vector<char> vChar; int testInt = 67; char testChar = 'x'; char printChar; vChar.push_back(testInt); vChar.push_back(testChar); while (!vChar.empty()) { printChar = vChar.back(); vChar.pop_back(); cout << printChar << endl; } return 0; } |
上面的代码将输出" x C",这是不正确的,因为" cout"将" printChar"打印为char而不是int,而67是ASCII中的C。
我可以将" int"强制转换为" printChar",但这将使其输出" 120 67",这仍然是不正确的。 我还尝试使用条件来检测哪个是数字,哪个是字符。
1 2 3 4 5 6 7 8 9 10 | while (!vChar.empty()) { printChar = vChar.back(); vChar.pop_back(); if (isdigit(printChar)) { cout << int(printChar) << endl; } else { cout << printChar << endl; } } |
但是永远不会触发" isdigit()",并且结果与没有" int"强制转换的结果相同...
如何使用" char"类型正确打印/输出数字和字符的字符串?
PS。 我正在为我的学校项目计算矩阵,并强制将char用于符号矩阵,因此我必须以某种方式能够使用char存储字符和整数,同时将它们彼此区分。
How can I correctly print/output string for both numbers and characters using"char" type?
一种选择是存储其他信息。
而不是使用
1 | vector<char> vChar; |
采用
1 2 3 | // The first of the pair indicates whether the stored value // is meant to be used as an int. vector<std::pair<bool, char>> vChar; |
接着
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | vChar.push_back({true, testInt}); vChar.push_back({false, testChar}); while (!vChar.empty()) { auto printChar = vChar.back(); vChar.pop_back(); if ( printChar.first ) { cout << (int)(printChar.second) << endl; } else { cout << printChar.second << endl; } } |