Search code examples
c++arraysgetlinec-strings

copying contents from one char array to another but getting junk


I am accepting a user input in the format (123) 456-7890 and storing it into a char array per my assigned instructions. I want to copy JUST THE NUMBERS of that input into another array so I have 1234567890 and leave out the ( ) -.

I get the originally formatted user input by using cin.getline() and I use a for loop to transfer just the numbers into the second array but I get a bizarre output. Here is the code:

int main()
{
    const int MAX = 15, dMAX = 10;

    char nums[MAX], digit[dMAX];
    int usableN, rdx = 0;


    cout << "Enter phone number in (XXX) XXX-XXXX format:  ";
    cin.getline(nums, MAX);

    for (int i = 1; i < 4; i++)
    {
        digit[rdx] = nums[i];
        usableN = atoi(digit);
        cout << digit << endl;
        rdx++;
    }

    for (int i = 6; i < 9; i++)
    {
        digit[rdx] = nums[i];
        usableN = atoi(digit);
        cout << digit << endl;
        rdx++;
    }

    for (int i = 10; i < 14; i++)
    {
        digit[rdx] = nums[i];
        usableN = atoi(digit);
        cout << digit << endl;
        rdx++;
    }

    cout << endl << digit << endl;

    return 0;
}

For now, ignore usableN = atoi(digit); because that is for later use. The multiple cout << parts are so I can see what is being stored at each step. Now, this is the part I can't understand and need help with:

My output is full of junk and despite the fact that I used const int dMAX = 10; my array is 24 characters long. Here is the output:

7Ss╨vJs╨vπ(789) 678-1234
78s╨vJs╨vπ(789) 678-1234
789╨vJs╨vπ(789) 678-1234
7896vJs╨vπ(789) 678-1234
78967Js╨vπ(789) 678-1234
789678s╨vπ(789) 678-1234
7896781╨vπ(789) 678-1234
78967812vπ(789) 678-1234
789678123π(789) 678-1234
7896781234(789) 678-1234

7896781234(789) 678-1234

Why is it copying the entirety of nums[] on the tail of digit[] ?

How do I get a clean array with just the 7896781234 in it?

Also, I noticed that whenever I cin.getline(nums, MAX), if the user inputs more than MAX characters, it crashes! Why is this and how do I prevent this?

I thought that cin.getline would only store the fist nth characters defined by MAX

Sorry, this was a lengthy explanation but I wanted to make sure I was clear on what I was asking. Thanks in advance for any help on these issues.


Solution

  • You need to make sure your strings are always null terminated. For example:

    for (int i = 1; i < 4; i++)
    {
        digit[rdx] = nums[i];
        digit[rdx+1] = '\0';
        usableN = atoi(digit);
        cout << digit << endl;
        rdx++;
    }