我正在研究一个将十进制输入转换为十六进制等效项的程序。我计划使用矢量系统地收集值,然后反向吐出它们(因此以十六进制形式)。但是我遇到了很多问题。所有输入直到16按预期工作,然后事情变得奇怪。输入16会导致系统输出笑脸,输入18个结果导致2个不同颜色的笑脸,23导致系统发出蜂鸣声。
这应该是一个相对简单的代码,它只是以我从未见过的方式表现出来!希望这些信息有帮助
编辑:我知道std :: hex函数,虽然这是针对一个类而且我们不允许使用它unfortunatley。
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main(){
int input, tester = 0, switchStuff, county = 0, remainderCount = 1, inputCount, remainder = 1, remainderCount2, inputCount2;
string stopGo;
char remainderLetter;
do{
while (tester != 1){
cout << "Enter the number you would like to convert to Hex format: ";
cin >> input;
if (cin.fail()){ //check if user input is valid
cout << "Error: that is not a valid integer.\n";
cin.clear(); cin.ignore(INT_MAX, '\n'); //Clear input buffer
continue; //continue skips to top of loop if user input is invalid, allowing another attempt
}
else{
tester = 1; //Tester variable allows loop to end when good value input
}
}
inputCount = input;
while(inputCount != 0){
remainderCount = inputCount % 16;
inputCount = (inputCount - remainderCount) / 16;
county++;
}
vector<string>userInfo(county);
inputCount2 = input;
for (int i = 0; county > i; i++){
remainderCount2 = inputCount2 % 16;
inputCount2 = (inputCount2 - remainderCount2) / 16;
if (remainderCount2 == 10){
remainderLetter = 'A';
}
else if (remainderCount2 == 11){
remainderLetter = 'B';
}
if (remainderCount2 == 12){
remainderLetter = 'C';
}
else if (remainderCount2 == 13){
remainderLetter = 'D';
}
if (remainderCount2 == 14){
remainderLetter = 'E';
}
else if (remainderCount2 == 15){
remainderLetter = 'F';
}
if (remainderCount2 >= 10){
userInfo[i] = remainderLetter;
}
else{
userInfo[i] = remainderCount2;
}
}
cout << "The result in Hexadecimal format is: ";
for (int i = 0; i < county; i++)
cout << userInfo[i];
cout << endl << "Would you like to continue? (Enter Yes/No): "; //Check whether to continue or not
cin >> stopGo;
cout << endl;
tester = 0;
}while ((stopGo.compare("Yes") == 0) || (stopGo.compare("yes") == 0) || (stopGo.compare("y") == 0) || (stopGo.compare("Y") == 0)); //Leaves user with a range of ways to say 'yes'
cout << "Thank you for using this program!" << endl;
system("pause");
}
答案 0 :(得分:0)
尝试更改
userInfo[i] = remainderCount2;
到
userInfo[i] = remainderCount2 + '0';
(&#39;导致数字0,1,...与char&#39; 0&#39;,&#39; 1&#39;,...)
不同顺便说一句,有一种简单的方法可以将dec转换为十六进制
std::string sDecimal[] = "155";
char xHex[50];
sprintf(xHex, "%X", atoi(sDecimal.c_str()));