I have a program that should translate values from one number system to another, but I have a problem with "_itoa_s" writes that [Error] '_itoa_s' was not declared in this scope I tried to connect libraries <cstdlib> and <stdlib.h> I also tried replacing itoa with "snprintf" but it does not help in the compiler there are even more errors, please help me fix the error,
Here is the code:
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
setlocale(LC_ALL, "rus");
int in, iz, k, s = 0, p;
char str[255];
cout << "Enter the number system from which you want to translate" << endl;
cin >> iz;
cout << "Enter the number system to which we will translate" << endl;
cin >> in;
cout << "Enter the number" << endl;
cin >> str;
p = strlen(str) - 1;
for (int i = 0; i < str[i]; i++)
{
switch (str[i])
{
case 'a': k = 10; break;
case 'b': k = 11; break;
case 'c': k = 12; break;
case 'd': k = 13; break;
case 'e': k = 14; break;
case 'f': k = 15; break;
case '1': k = 1; break;
case '2': k = 2; break;
case '3': k = 3; break;
case '4': k = 4; break;
case '5': k = 5; break;
case '6': k = 6; break;
case '7': k = 7; break;
case '8': k = 8; break;
case '9': k = 9; break;
case '0': k = 0; break;
}
s = s + k * pow(iz, p);
p--;
}
char result[255];
_itoa_s(s, result, in);
cout << "The result of a translation from a radix " << iz << " to radix " << in << " = " << result;
return 0;
}
Here's an alternative that doesn't involve switch, pow or itoa:
// Notice, the index is the value of the digit.
const std::string digits[] = "0123456789abcdef";
//...
const size_t length = str.len;
// Note: iz is the radix for "input" conversion
int number = 0;
for (unsigned int i = 0; i < length; ++i)
{
const std::string::size_type position = digits.find(str[i]);
number = number * iz; // Shift the number by one digit.
number += position;
}
Notice: error handling, such as invalid digits, is left as an exercise for the OP. Invalid digits are not restricted to characters outside the set, but also digits whose index is greater than the conversion radix.
For ultimate understanding, single step through the code with pen and paper. :-)
You can use the table for converting to the target radix, in (I'd rather use a more descriptive variable name).
std::string translated_number;
while (number > 0)
{
const unsigned int index = number % output_radix; // Output_radix == 'in'
const char digit_character = digits[index];
translated_number.insert(0, 1, digit_character);
number = number / output_radix;
}
Related
This program gets two hexadecimal numbers and converts them to decimal numbers. And it finally returns sum of two number in decimal form.
Before I enter "num2", "n1" gets right value.
But "n1" becomes 0 after I get "num2".
I don't know why this happens.
Please tell me the reason in hurry...
#include <iostream>
using namespace std;
class HextoDec {
public:
void getNum();
int add();
private:
char num1[2], num2[2];
int convert(char num[]);
int n1, n2;
};
int main()
{
HextoDec a;
a.getNum();
cout << "Sum of two number is " << a.add() << endl;
}
void HextoDec::getNum() {
cout << "Enter first number : ";
cin >> num1;
n1 = convert(num1);
cout << "Enter second number : ";
cout << endl << n1 << endl; // Value of n1 is correct
cin >> num2;
cout << n1 << endl; // Problem occurs. Value of n1 becomes 0
n2 = convert(num2);
}
int HextoDec::convert(char num[]) {
int j = 16, n = 0;
for (int i = 0 ; i < 2 ; i++) {
switch (num[i]) {
case '0':
n = n + j * 0; break;
case '1':
n = n + j * 1; break;
case '2':
n = n + j * 2; break;
case '3':
n = n + j * 3; break;
case '4':
n = n + j * 4; break;
case '5':
n = n + j * 5; break;
case '6':
n = n + j * 6; break;
case '7':
n = n + j * 7; break;
case '8':
n = n + j * 8; break;
case '9':
n = n + j * 9; break;
case 'A':
n = n + j * 10; break;
case 'B':
n = n + j * 11; break;
case 'C':
n = n + j * 12; break;
case 'D':
n = n + j * 13; break;
case 'E':
n = n + j * 14; break;
case 'F':
n = n + j * 15; break;
}
j = 1;
}
return n;
}
int HextoDec::add() {
cout << "*****" << endl;
cout << n1 << endl;
cout << n2 << endl;
return n1 + n2;
}
What's the reason?
What makes this happens?
What can I do or should I do to solve this problem?
As other people have mentioned, your char arrays only contain one element, plus the '\0' character. If you try to read with cin a two character array (i.e. 1a) you will have a undefined behaviour. This example might give you some hints about '\0'
const char *example1 = "hi";
strlen(example1); // This is 2
const char *example1 = "hi\0";
strlen(example1); // This is also 2
But answering to your question, if you only want to read 2-digit hexadecimal values, char num1[3] should fix the issue.
However, I think you might have another issue. Just copied/pasted your code and if I enter just 1 the result that I get is 16, but it should be 1. Maybe you expect the user to input 01 instead.
I guess this is a didactic example, so you might want to play a bit with the code, and for example be able to convert any number to decimal. Maybe you can modify your function convert with something like:
int HextoDec::convert(char num[]) {
int n = 0;
int sizeNumber = strlen(num);
for (int i = sizeNumber - 1; i >= 0; i--)
{
int j = pow(16, sizeNumber - i - 1);
...
}
I was trying to make a program to convert Roman numerals to arabic numeral, but for some reason when he gets to the function setNumeri, the input text gets messed up super badly even before it can even get to the conversion part.
The problem is the function setNumeri, you can ignore everything else, because I pasted everything to be sure not to leave anything out.
I apologize for the fact that some variables are in Italian, but it should be pretty straightforward.
Here's the code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
class IX{
public:
void setNumeri(string rom);
void setArabo();
int getArabo();
private:
int length;
int Arabo;
int Numeri[];
};
void IX::setNumeri(string rom){
length = rom.length();
for(int i = length - 1; i >= 0; i--) {
cout << rom.at(i) << endl;
switch (rom.at(i)){
case 'I':
Numeri[i] = 1;
break;
case 'V':
Numeri[i] = 5;
break;
case 'X':
Numeri[i] = 10;
break;
case 'L':
Numeri[i] = 50;
break;
case 'C':
Numeri[i] = 100;
break;
case 'D':
Numeri[i] = 500;
break;
case 'M':
Numeri[i] = 1000;
break;
}
}
}
void IX::setArabo(){
int counter = Numeri[length];
for(int i = length - 1; i >= 0; i--){
if(Numeri[i] == 0) {
counter = counter + Numeri[i];
} else if(Numeri[i] > Numeri[i-1]) {
counter = counter - Numeri[i-1];
i--;
} else if(Numeri[i] <= Numeri[i-1]) {
counter = counter + Numeri[i-1];
}
}
Arabo = counter;
}
int IX::getArabo(){
return Arabo;
}
int main(){
IX lol;
string hellothere;
cout << "Roman numeral:" << endl << endl;
cin >> hellothere;
lol.setNumeri(hellothere);
cout << lol.getArabo() << endl;
return 0;
}
When I input XIII, the output is:
I
I
□
-107362937
That last ominous number is the result of the conversion, while the first 3 characters (one is missing in action, and one is not recognised at all) are the output by string.at() that, as you can see, did a wonderful job getting the string characters right. Tried using string[] instead but no success.
What's even weirder is the fact that once I deleted the whole switch case string.at() gets the string right, it looks like the string gets somehow messed up during the switch part. The same happens using an if statement instead of the switch.
Thanks in advance.
try following code it is working perfectly fine.
#include <cstdlib>
#include <string>
using namespace std;
class IX{
public:
void setNumeri(string rom);
int getArabo();
private:
int length;
int Numeri[100];
};
void IX::setNumeri(string rom){
length = rom.length();
for (int i = 0; i < 100; i++)
{
Numeri[i]=-1;
}
for(int i = length - 1; i >= 0; i--) {
cout << rom.at(i) << endl;
switch (rom.at(i)){
case 'I':
Numeri[i] = 1;
break;
case 'V':
Numeri[i] = 5;
break;
case 'X':
Numeri[i] = 10;
break;
case 'L':
Numeri[i] = 50;
break;
case 'C':
Numeri[i] = 100;
break;
case 'D':
Numeri[i] = 500;
break;
case 'M':
Numeri[i] = 1000;
break;
}
}
}
int IX::getArabo(){
int sum=0;
for (int i = 0; i < 100; i++)
{
if (Numeri[i]==-1)
{
return sum;
}
else
{
sum+=Numeri[i];
}
}
}
int main(){
IX lol;
string hellothere;
cout << "Roman numeral:" << endl << endl;
cin >> hellothere;
lol.setNumeri(hellothere);
cout << lol.getArabo() << endl;
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want my function to read one char[] and split it into 2 arrays. Both arrays would be one big number, first array is for that number int value and second one is for double values. I must use 2 arrays because this number can be binary, decimal, octal or hex.
void Read(int place[], int &size, int &type, int placedot[], int &sizedot, int &typedot)
{
char reader[limit];
cin >> reader;
size = 1;
while (reader[size] == '.' || size != strlen(reader))
{
size++;
cout << "LOL";
}
cin >> type;
cout << size;
typedot = type;
for (int i = 0; i<size; i++)
{
switch (reader[i])
{
case '0': place[i] = 0; break;
case '1': place[i] = 1; break;
case '2': place[i] = 2; break;
case '3': place[i] = 3; break;
case '4': place[i] = 4; break;
case '5': place[i] = 5; break;
case '6': place[i] = 6; break;
case '7': place[i] = 7; break;
case '8': place[i] = 8; break;
case '9': place[i] = 9; break;
case 'A': place[i] = 10; break;
case 'B': place[i] = 11; break;
case 'C': place[i] = 12; break;
case 'D': place[i] = 13; break;
case 'E': place[i] = 14; break;
case 'F': place[i] = 15; break;
}
}
}
#include <iostream>
#include <string>
int main()
{
std::string str = "3423432432.32445654576654578978905";
std::string strInt;
std::string strDec;
int i = 0;
while('.' != str[i])
strInt += str[i++];
for(++i; i < str.length(); i++)
strDec += str[i];
std::cout << strInt << std::endl << strDec << std::endl;
// now you have the integer part and the decimal part as strings so convert each of them to int
std::cout << std::endl;
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i have a program and i should convert int to char into it
but i cant use itoa() because site's judge don't support it
so i wrote this:
xt[i]= rmn+'0';
but i get this error :
Runtime error: Illegal file open (/dev/tty)
How should i convert this?
My code is this : (for palsquare question of USACO)
/*
ID: sa.13781
PROG: palsquare
LANG: C++
*/
#include <iostream>
#include <fstream>
using namespace std;
ofstream fout("palsquare.out");
int tool(char xt[])//CORRECT
{
int p = 0;
while (xt[p] != 0)
p++;
return p;
}
void prt(char xt[])//CORRECT
{
int p = 0;
while (xt[p] != 0)
{
fout << xt[p];
p++;
}
}
void mabna(int a, char xt[], int mab)
{
int ex = 1, tavan = 0, rmn, n;
for (; ex <= a; ex *= mab)
tavan++;
for (int i = tavan - 1; a != 0; i--, a /= mab)
{
rmn = a % mab;
switch (rmn)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
xt[i] = rmn + '0';
break;
case 10:
xt[i] = 'A';
break;
case 11:
xt[i] = 'B';
break;
case 12:
xt[i] = 'C';
break;
case 13:
xt[i] = 'D';
break;
case 14:
xt[i] = 'E';
break;
case 15:
xt[i] = 'F';
break;
case 16:
xt[i] = 'G';
break;
case 17:
xt[i] = 'H';
break;
case 18:
xt[i] = 'I';
break;
case 19:
xt[i] = 'J';
break;
}
}
}
bool mirror(char *xt)//CORRECT
{
int p = 0;
int n = tool(xt);
for (int i = 0; i < (n / 2); i++)
if (xt[i] == xt[n - i - 1])
p++;
if (p == (n / 2))
return true;
return false;
}
void calc(int mab) //CORRECT
{
for (int i = 1; i <= 300; i++)
{
char p[10] = {0}, p2[10] = {0};
mabna(i * i, p2, mab);
if ( mirror(p2) == true )
{
mabna(i, p, mab);
prt(p);
fout << " ";
prt(p2);
fout << "\n";
}
}
}
int main()
{
ifstream fin("palsquare.in");
int mab;
fin >> mab;
calc(mab);
return 0;
}
Can you use sprintf()?
char s[16];
int x = 15;
sprintf(s, "%d", x);
If your int value is single digit, you can just cast it with (char)
If your int value is more than one digit, you can never expect a single char to hold it. char can only hold single character.
int num = 7;
char ch = (num + 48); //same effect as + '0'
cout << ch << endl;
OUTPUT: 7
If your int value is more than single digit. You need char* or char[] to hold the converted data. For example:
int num = 123987;
int len = 6;
int idx = len-1;;
char ch[20];
while(num > 0)
{
ch[idx] = (num%10) + 48;
num /= 10;
idx --;
}
for(int x=0; x<len; x++)
cout << "OUTPUT in char: " << ch[x];
OUTPUT in char: 123987
This is not a perfectly good way to handle this kind of situation, but it may gives you what you asked for.
I have some code pasted here that keeps giving me the error in the title whenever more than one number is given as input. I cannot find one place where inputValue is being improperly accessed, but I could use another (few) sets of eyes. Thanks for any help ahead of time!
// descriptions of declared functions listed with implementation
int ProcessInput(const int fromBase, const int toBase, char inputValue[],
const int length);
void ConvertToBase(int decimal, const int inBase, char outPut[]);
double Exponent(const int number, const int exponent);
int main(int argsc, char** argsv)
{
int fromBase(0), toBase(0);
// set bases and initialize vector for storing output until end of input
fromBase = atoi(argsv[1]);
toBase = atoi(argsv[2]);
vector <char *> outPutValues;
int count(0);
while (!cin.eof())
{
// array to hold input value
char inputValue[8] = {' '};
// receive input from keyboard and convert input to decimal and new base
while (cin >> inputValue)
{
int length(strlen(inputValue));
// using dynamic arrays in vector allows for multiple input
// with no output until all input received
outPutValues.push_back(new char[8]);
int decimalValue = ProcessInput(fromBase, toBase, inputValue,
length);
// if the new base is decimal, simply output decimalValue;
// else process the new base and store in an output array;
ConvertToBase(decimalValue, toBase, outPutValues[count]);
count++;
}
for (int c = 0; c < outPutValues.size(); c++)
{
int k(0);
// display only set values of the output array
while ((outPutValues[c][k] == '\0') || (outPutValues[c][k] == '0'))
k++;
while (k < 8)
{
cout << outPutValues[c][k];
k++;
}
cout << endl;
}
}
// free up dynamic arrays
for (int d = 0; d < outPutValues.size(); d++)
delete outPutValues[d];
return 0;
} // end main
// ProcessInput receives the input array and translates the char values
// into a decimal value to be returned to calling function
int ProcessInput(const int fromBase, const int toBase, char inputValue[],
const int length)
{
int exponent(0), decimalValue(0);
for (int j = 0; j < length; j++)
{
exponent = (length - j - 1);
// convert inputValue from char to int to be processed into decimal;
// negative signs are ignored
switch (inputValue[j])
{
case 'a':
case 'A': decimalValue += (10 * Exponent(fromBase, exponent)); break;
case 'b':
case 'B': decimalValue += (11 * Exponent(fromBase, exponent)); break;
case 'c':
case 'C': decimalValue += (12 * Exponent(fromBase, exponent)); break;
case 'd':
case 'D': decimalValue += (13 * Exponent(fromBase, exponent)); break;
case 'e':
case 'E': decimalValue += (14 * Exponent(fromBase, exponent)); break;
case 'f':
case 'F': decimalValue += (15 * Exponent(fromBase, exponent)); break;
case '-': cout << "Negative Number Received. Converted to unsigned int.\n"; break;
default: decimalValue += ((inputValue[j] - '0') * Exponent(fromBase, exponent)); break;
}
}
return decimalValue;
} // end ProcessInput
// ConvertToBase converts the decimal form of a number into
// a new base by dividing the decimal until 0 and
// storing the remainders in the output array
void ConvertToBase(int decimal, const int inBase, char outPut[])
{
int remainder(0);
// char variable used to convert int back into char
// for output
char intToChar('0');
for (int i = 7; i >= 0; i--)
{
remainder = decimal % inBase;
decimal /= inBase;
// account for hex and if remainder is an int,
// store as char in output array using char intToChar
switch (remainder)
{
case 10: outPut[i] = 'A'; break;
case 11: outPut[i] = 'B'; break;
case 12: outPut[i] = 'C'; break;
case 13: outPut[i] = 'D'; break;
case 14: outPut[i] = 'E'; break;
case 15: outPut[i] = 'F'; break;
default: for (int j = 0; j < remainder; j++) {intToChar++;}
outPut[i] = intToChar;
intToChar = '0';
break;
}
}
} // end ConvertToBase
// converts input to decimal form by multiplying
// each number place by its base and exponent
double Exponent(const int number, const int exponent)
{
double value(1);
for (int i = 1; i <= exponent; i++)
value *= number;
return value;
} // end Exponent
#JeffA. you are missing the trailing \0. – erikced
Yes sir, just saw this right before I saw your answer. I need that extra element for the null terminator. Thanks! I know this project is messy and more C than C++, but the template is what it is. Thanks for all the help guys and gals!