'How can I convert an array of characters to an integer (for 2 or more digits)
The array has to be entered by the user, and not specified in the app itself.
char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
cin >> coeff[i];
cin >> expo[i];
}
When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?
PS. I'm forced into using an array of characters here and not integers
Solution 1:[1]
You're storing it in char array. Change the type of coeff and expo to the right one. Eg: int coeff[20] if you expect to store 20 ints.
Solution 2:[2]
This is technically possible but with limitation. In C++ char size is usually 1 byte (check first comment) while int size is 4 bytes, so the largest value you can store in a char is maximum 255 (check first comment) because 255 is the largest number that can be represented with only 1 byte.
So in the for loop you can use a new int variable to store in it the user input, and then store the bytes in the char variable.
And when trying to get the stored integer cast it to an int like:
char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
int x = 0;
cin>>x;
coeff[i] = (char) x;
cout<<(int) coeff[0];
}
Solution 3:[3]
I recommend directly using int variables instead of char arrays. But as you have to do it for your homework, I found a way to input data into a char array:
istream& operator>> (istream& is, char char_array[INT_MAX]) // INT_MAX means the maximum value for an int
{
std::string s; is >> s;
if (s.size() > 20) s = s.substr(0, 20);
for (int i = 0; i < s.size(); i++)
{
char_array[i] = s[i];
}
return is;
}
Here I am overloading the operator >> to work with char arrays of size INT_MAX.
Then in your main function, you can simply say:
int main()
{
char char_array[20]{};
std::cin >> char_array;
for (int i = 0; i < sizeof(char_array); i++)
{
std::cout << char_array[i];
}
}
As simple as that. Also according to the code that you submitted, don't do the following:
using namespace std;
...as it is considered as bad practice. I know there are better ways than this but this is just my idea.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anirudh |
| Solution 2 | Andreas Wenzel |
| Solution 3 | Dharman |
