c++ - copying contents from one char array to another but getting junk -


i accepting user input in format (123) 456-7890 , storing char array per assigned instructions. want copy numbers of input array have 1234567890 , leave out ( ) -.

i formatted user input using cin.getline() , use for loop transfer numbers second array bizarre output. here 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);      (int = 1; < 4; i++)     {         digit[rdx] = nums[i];         usablen = atoi(digit);         cout << digit << endl;         rdx++;     }      (int = 6; < 9; i++)     {         digit[rdx] = nums[i];         usablen = atoi(digit);         cout << digit << endl;         rdx++;     }      (int = 10; < 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 later use. multiple cout << parts can see being stored @ each step. now, part can't understand , need with:

my output full of junk , despite fact used const int dmax = 10; array 24 characters long. here 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 copying entirety of nums[] on tail of digit[] ?

how clean array 7896781234 in it?

also, noticed whenever cin.getline(nums, max), if user inputs more max characters, crashes! why , how prevent this?

i thought cin.getline store fist nth characters defined max

sorry, lengthy explanation wanted make sure clear on asking. in advance on these issues.

you need make sure strings null terminated. example:

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

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -