This question already has answers here:
Convert char to int in C and C++
(14 answers)
Closed 1 year ago.
could someone try explain the what the difference between these two pieces of codes is?
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int idx = 2;
string digits = "1324";
int curidx=digits[idx] - '0';
cout << curidx << endl;
}
In this case, with the inclusion on line 12, the output is 2.
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int idx = 2;
string digits = "1324";
int curidx=digits[idx];// - '0';
cout << curidx << endl;
}
In this result, the output result is 50. What does the inclusion of - '0' do?
In C and Cpp, everything is inherently treated as a "number". Even char manipulations should be treated as number-operations...that makes it easier to logic-out the requirements.
Every char is indeed, an integer, equivalent to its ASCII value.
Hence, '2' = 50. Also, 'A' = 65 and 'a' = 97 and so on...
So, your operation '2' - '0' actually does 50-48, which results in 2
When you do not subtract and print '2' as integer, it prints its ascii value, which is 50. If you would print it as a char or string, it would have printed 2.
Related
I have this string str . I want to Multiply value of each position of string with 7 or any value. First I used string Function str.at() and stored in a new char type variable, but when i multiplied the index 0 value: 9 with 7 it's giving me 399 instead of 63. I have also tried this without a string function, like this: char s = str[0]; and then multiplied s with 7 but i'm still not getting the correct answer.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "9958721";
char s = str[0];
cout << s * 7;
cout << "\nPROGRAM ENDED...";
return 0;
}
That's because '9' ASCII code is 57. See
To get the expected result use something like the following
string str = "9958721";
char s = str[0];
cout << 7 * (static_cast<int>(s) - static_cast<int>('0'));
to subtract the equivalent ASCII value of zero. Note that they are ordered.
And see Why is "using namespace std;" considered bad practice?
I'm working on this code that takes a numeric string and fills an array with each "digit" of the string. The issue I'm having is trying to convert an integer to a string. I tried using to_string to no avail.
Here is the code (note this is pulled from a larger program with other functions):
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <typeinfo>
int fillarr(int &length) {
int arr[length];
string test = "10010"; //test is an example of a numeric string
int x = 25 + ( std::rand() % ( 10000 - 100 + 1 ) );
std::string xstr = std::to_string(x); //unable to resolve identifier to_string
cout << xstr << endl;
cout << typeid (xstr).name() << endl; //just used to verify type change
length = test.length(); //using var test to play with the function
int size = (int) length;
for (unsigned int i = 0; i < test.size(); i++) {
char c = test[i];
cout << c << endl;
arr[int(i)] = atoi(&c);
}
return *arr;
}
How can I convert int x to a string? I have this error: unable to resolve identifier to_string.
As mentioned by user 4581301, you need an #include <string> to use string functions.
The following, though is wrong:
arr[int(i)] = atoi(&c);
The atoi() will possibly crash because c by itself is not a string and that mean there will be no null terminator.
You would have to use a buffer of 2 characters and make sure the second one is '\0'. Something like that:
char buf[2];
buf[1] = '\0';
for(...)
{
buf[0] = test[i];
...
}
That being said, if your string is decimal (which is what std::to_string() generates) then you do not need atoi(). Instead you can calculate the digit value using a subtraction (much faster):
arr[int(i)] = c - '0';
Okay I modified my code a bit per suggestion from everyone and ended up handling the conversion like this:
string String = static_cast<ostringstream*>( &(ostringstream() << x) )->str();
cout << String << endl;
This question already has answers here:
Array size at run time without dynamic allocation is allowed? [duplicate]
(8 answers)
Closed 7 years ago.
I receive these errors
1. cannot allocate an array of constant size 0
2. expected constant expression
3. 'numbers' : unknown size
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int input_num;
int sum;
cout << "Enter the number:" << endl;
getline(cin, str);
const int length = str.length();
cout << "Length:" << length<<endl;
//input_num = stoi(str);
int numbers[length];
return 0;
}
Replace the use of an array by a std::vector, and initialize the elements to 0.
std::vector<int> numbers(length, 0);
The size of an array has to be a constant expression greater than 0.
You should use standard class std::vector<int> instead.
For example
#include <vector>
//...
std::vector<int> numbers( length );
If the user has to enter a number of type for example int (that is the number might be in the range of acceptable values of object of type int) then you could define the array beforehand the following way
#include <limits>
//...
int numbers[std::limits<int>::digits10 + 1];
I am a high school beginner to C++ (Less than 1 month since I started). I have been trying to convert a int into its char value. (So, a 5 should convert to a '5')
I am aware how to convert from char to int (from '5' to 5), by subtracting 48 from it, however I am unable to cast the other way. Here's what I tried:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout<<x<<endl;
cout<<(char)x<<endl;
cout<<static_cast<char>(x)<<endl;
cout<<"end of program"<<endl;
}
The output I get is
5
end of program
I am unsure why I don't get an output. Appreciate any advice.
The cast is working perfectly fine (for what you're doing).
You're casting a 5 to it's ASCII value. Look at an ASCII table and see what a 5 represents.
Now for what you're trying to do, try cout << (char)(x+48) << endl;
Try the following
#include <iostream>
using namespace std;
int main()
{
int x = 5;
cout << x << endl;
cout << ( char )( x + '0' ) << endl;
cout << static_cast<char>( x + '0' ) < <endl;
cout << "end of program" < <endl;
}
And you have not to look through ASCII table.:) Take into account that there is EBCDIC table. The code I showed does not depend on a coding table. The C++ Standard guarantees that all characters of digits follow each other starting from '0' to '9'.
This question already has answers here:
Convert char to int in C and C++
(14 answers)
Closed 9 years ago.
My code is this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int a;
cout << "Enter a number" << endl;
cin >> a;
string a_str;
ostringstream temp;
temp << a;
a_str = temp.str();
for(int i = 0; i < a_str.length(); i++) {
char c = a_str[i]; //How this character convert to integer number
}
system("pause");
return EXIT_SUCCESS;
}
How char c convert to int ?
I need this for
I need this because I need to get the highest digit
If you want to get char '8' to int 8 for example, this would be enough for ascii
int i = a_str[0] - '0';
const int i = atoi(&c);
should work too
char is already an integral type. I think you meant the following
char c = a_str[i] - '0';
atoi(c) for integers
atof(c) for floats
do the trick
You can also write it yourself:
This works for normal keys (not arrows keys or...)
#include <iostream>
using namespace std;
int main () {
char c;
cin >> c;
cout << (int)c << endl;
}
if you just have digits, you can do this:
int num = c - '0';