0
string myString="";
int c;
int arrayMain1[100]={0}, arrayMain2[100]={0},arrayMain3[100]={0};

cout << "Input Number" << endl;

cin >> myString;

cout << myString[0]<<endl;
if(myString.length()<=100)
{
    c=99;
    for(int i=myString.length();i>=0;i--)
    {
        //cout << myString[i];
        arrayMain1[c]=myString[i];
        c--;
    }

    for(int j=0;j<=100;j++)
    {
        cout << arrayMain1[j];
        //cout << myString[j];
    }
}

Here is my code, its suppose to copy the string I input to the end of an array. If my input string is '1234' the array would look, 0000....1234. For some reason when I print the array, it prints wrong numbers.

0

3 Answers 3

1

One error is that you should start from myString.length() - 1

for(int i=myString.length() - 1;i>=0;i--) 

Another error is that j loop should loop upto 99

for(int j=0;j<=99;j++)

Also, while assigning the char to an int, you will have to subtract the ASCII value of '0'.

arrayMain1[c]=myString[i] - '0';
Sign up to request clarification or add additional context in comments.

3 Comments

Good catches on these limits
@AbhishekBansal thank you, can you please explain the significance of substracting '0'??
@user2086751 myString[i] returns a char not an int. To convert it to int, you will have to subtract the ASCII value of '0' character. This is because all the digits ('0' to '9') are stored sequentially in the ASCII table. Google for ASCII table and you will understand.
0

Strings are stored as an array of chars. Your arrayMainN arrays have elements with type int. C++ will implicitly convert chars to ints via the ASCII table, which (unfortunately?) doesn't map the char '1' to the int 1 and so on.

So, you need to convert your chars to ints before storing them in the array. The idiomatic way to do this is

int ctoi(char c) {
    return c - '0';
}

// example usage
char mychar = '8';
cout << ctoi(mychar);  // prints 8

You would change your code like this:

arrayMain1[c]=ctoi(myString[i]);

Comments

0

There are two things to point. First, there's a type mismatch. I've been in C/C++ for about two years. And frankly, I'm not sure if I'm getting this right, but I think, you are converting char to int. And that scramble the things. Like say, there was a 1 in the string. But it was as a char, when you are converting this as an int, you get the ASCII value for 1(As far as I remeber, it should be around 48). That makes the problem here. And one thing else to point (I'm pretty not sure about this.) that your are getting that as reverse. Like, if you type in 1234, you should get that as 4321.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.