Hi, what I'm trying to accomplish is calling a function with a string and then taking that string and turning it into an integer. The way I could think of doing this was taking the c++ string and copying it to an array that would cycle through and convert it cell by cell ? I get an output that is garbage however and I'm unsure of what to do next.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Integer::Integer(string s)
{
char b[MAXDIGITS+1];
strcpy_s(b,MAXDIGITS,s.c_str());
int size;
size = s.length();
int y = size - 1;
for(size_type x = MAXDIGITS - 1; x >= 0 ; x--, y--)
{
a[x] = int(b[y]-'0');
};
}
Im not very familiar with how youre coding, but i found this example. looks like you need to know atoi function (btw you code looks jumbled and hard to read use the [ code ] [ / code] and place your code between them.)
1 2 3 4 5 6 7 8 9 10
int main ()
{
int i;
char szInput [256];
printf ("Enter a number: ");
fgets ( szInput, 256, stdin );
i = atoi (szInput);
printf ("The value entered is %d. The double is %d.\n",i,i*2);
return 0;
}
Oh yeah sorry, its Visual C++ OOP thats a constructor for my class and when I call it with a string I wanted it to copy to an array that i could then go index by index and then type cast to int. The problem is however, it outputs garbage and im not sure why.
A string already behaves like a character array, that is, you can access it's elements with the [ ] operator. No need to make a copy.
Oh, and here an easy algorithm (explained with an example) that works pretty well for integers:
String: "21942"
[single quotes mean "character"]
Go from left to right, take the first digit: '2'
Convert it to an integer: 2
Get the next digit: '1'
Convert it to an integer: 1
Multiply what you had before by 10 and add the new integer: 2*10 + 1 = 21
Get the next digit: '9'
Convert it to an integer: 9
Multiply what you had before by 10 and add the new integer: 21*10 + 9 = 219
etc etc. The reason this works should be obvious from the definition of a decimal number.
EDIT: Oh, and to convert a digit saved as a char to it's integer representation, you can just substract '0' ('8'-'0' = 8). Reason: look at the ascii table.
If your Integer is really supposed to have variable length (that's what "vli" stands for, right?), it can't have an array member. Array length is a constant. Consider using a vector<char> or just string.
@hanst99 Yeah lol its definitely not perfected its only my second semester.. But the default should be to initialize the private members. Im still toying around with this but im having no luck. Its printing out garbage but its still printing out.. Im in a bind xp
@Cubbi Very long integer. I know array length is constant, the max im allowing for input is 100 thanks