This question already has answers here:
Char to int conversion in C
(10 answers)
Convert an int to ASCII character
(11 answers)
Closed 6 years ago.
Can somebody explain me how the following tochar function works? As an experiment I added the following to tochar:
cout<<'0' + value
When run, I got a result of:
51 50 49 52
My code is:
static int tochar(int value)
{
return '0' + value;//This is the part i don't understand
}
int main()
{
char c[20];
int n = 4123;
int count = 0;
int number = log10(n)+1; //number of digits
for (int i = number; i >= 1; i--)
{
c[i] = tochar(n % 10);
n = n / 10;
count++;
}
for (int i = 1; i <=count; i++)
cout<<c[i];
system("pause");
}
You should change your function to
static char tochar(int value)
{
return '0' + value;//This is the part i don't understand
}
This function converts a single digit int to the character representing the digit. It assumes that 0-9 digits are consecutive in the char map, and works by computing the difference between the given argument and the '0' character.
Related
This question already has answers here:
Standard Input for Unsigned Character
(2 answers)
Closed 6 years ago.
I am working on some codes using c++.
Type char is one byte in my machine and int type is four bytes.
Since my input value is under 100, I used char type instead of integer type in order to make my process in an efficient way as shown in below codes.
int do_main(int argc, const char *argv[]) {
int TC;
cin >> TC;
while (TC--) {
unsigned char num;
char code[7];
for (int i = 0; i < 7; ++i) code[i] = 0;
cin >> num;
int idx = 0;
while (1) {
code[7-1-idx++] = num % 2;
num /= 2;
if (num < 2) break;
}
code[7 - 1 - idx] = num;
for (int i = 0; i < 7; ++i) cout << code[i] << endl;
}
return 0;
}
As you can see above codes, the 10 digit value is transformed into 2 bit type. However, my problem is that the value was not what I expected. it showed some strange character not 1 or zero.
I thought that it was due to the types. Therefore I modified the char into int and ran the codes again. I confirmed that the codes[i] showed the corrected value that I expected.
To summary.. my question is that what is wrong with the usage of char instead of int?
I know that char is aimed at storage of character but for some small integer value (up to 1 byte), we can use char instead of int type.
It is because std::cout's operator<<(char) is overloaded such that it will display ascii character corresponding to the digit. Instead of changing type from char to int, you can do like this
for (int i = 0; i < 7; ++i)
cout << static_cast<int>(code[i]) << endl;
See this.
This question already has answers here:
How compiler is converting integer to string and vice versa
(3 answers)
Closed 7 years ago.
I am trying to convert a string to a integer and carry out some arithmetic after that.
char string[10];
If the string has only one word I can do this:
string[0]-'0'
How can I convert it into an integer if the string has more than one character.
Better to use a built-in function, but if you want to do it by hand, you need to loop through all of the characters in the string that are actually digits. Since this is in base-10, you simply multiply an accumulator by 10 every time through the loop:
int strToInt (const char *str) {
int accumulator = 0;
int sign = 1;
if (*str == '-') {
str++;
sign = -1;
}
while (*str >= '0' && *str <= '9') {
accumulator *= 10;
accumulator += *str - '0';
str++;
}
return accumulator * sign;
}
int i,ans;
char num[] = "5678";
int l = strlen(num);
ans = 0;
for(i=0;i<l;i++)
ans = ans*10 + (num[i]-'0');
printf("%d\n",ans);
This question already has answers here:
How to convert a single char into an int [duplicate]
(11 answers)
Closed 7 years ago.
This code Find the sum of all digits that occur in a string.
Example
sumUpNumbers("2 apples, 12 oranges") = 5 //2+1+2
Can anyone explain the need for use int('0') in this code!?
int sumUpDigits(std::string inputString) {
int answer = 0;
for (int i = 0; i < inputString.size(); i++) {
if ('1' <= inputString[i] && inputString[i] <= '9') {
answer += int(inputString[i]) - int('0');
}
}
return answer;
}
It converts char into ASCII code to make number out of string
int('9') - int('0') = 9
This question already has answers here:
Convert single char to int
(3 answers)
Closed 3 years ago.
I have a string which has 5 characters. I want to convert each single character to int and then multiply them with each other. This is the code :
int main()
{
int x;
string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = atoi(str[i]);
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
cout<<x<<endl;
}
It gives this error for the line with atoi :
invalid conversion from 'char' to 'const char*' [-fpermissive]|
How can I fix this? Thanks.
You can use:
a[i] = str[i] - '0';
Does a char to digit conversion by ASCII character positions.
The proper way to do this is std::accumulate instead of rolling your own:
std::accumulate(std::begin(str), std::end(str), 1, [](int total, char c) {
return total * (c - '0'); //could also decide what to do with non-digits
});
Here's a live sample for your viewing pleasure. It's worth noting that the standard guarantees that the digit characters will always be contiguous, so subtracting '0' from any of '0' to '9' will always give you the numerical value.
std::atoi takes a const char*(a null terminated sequence of characters)
Try to change like
a[i]= str[i]-'0';
You are supplying with a single char hence the compiler is complaining
str[i] is char not char *
Use following :-
int x;
std::string str = "12345";
int a[5];
for(int i = 0; i < 5; i++)
{
a[i] = str[i] -'0' ; // simply subtract 48 from char
}
x = a[0]*a[1]*a[2]*a[3]*a[4];
std::cout<<x<<std::endl;
look at this way
string str = "12345";
int value = atoistr.c_str());
// then do calculation an value in a loop
int temp=1;
while(value){
temp *= (value%10);
value/=10;
}
This question already has answers here:
Counting the Frequency of Specific Words in Text File
(4 answers)
Closed 9 years ago.
I wrote a function for counting frequency of specific word in a text.This program every time return zero.How can I improve it?
while (fgets(sentence, sizeof sentence, cfPtr))
{
for(j=0;j<total4;j++)
{
frequency[j] = comparision(sentence,&w);
all_frequency+=frequency[j];
}}
.
.
.
int comparision(const char sentence[ ],char *w)
{
int length=0,count=0,l=0,i;
length= strlen(sentence);
l= strlen(w);
while(sentence[i]!= '\n')
if(strncmp(sentence,w,l))
count++;
i++;
return count;
}
I have proofread your code and have commented on coding style and variable names. There
is still a flaw I left with the conditional, which is due to not iterating through the
sentence.
Here is your code marked up:
while(fgets(sentence, sizeof sentence, cfPtr)) {
for(j=0;j<total4;j++){
frequency[j] = comparision(sentence,&w);
all_frequency+=frequency[j];
}
}
// int comparision(const char sentence[ ],char *w) w is a poor variable name in this case.
int comparison(const char sentence[ ], char *word) //word is a better name.
{
//int length=0,count=0,l=0,i;
//Each variable should get its own line.
//Also, i should be initialized and l is redundant.
//Here are properly initialized variables:
int length = 0;
int count = 0;
int i = 0;
//length= strlen(sentence); This is redundant, as you know that the line ends at '\n'
length = strlen(word); //l is replaced with length.
//while(sentence[i]!= '\n')
//The incrementor and the if statement should be stored inside of a block
//(Formal name for curley braces).
while(sentence[i] != '\n'){
if(strncmp(sentence, word, length) == 0) //strncmp returns 0 if equal, so you
count++; //should compare to 0 for equality
i++;
}
return count;
}