[C++][Question] Copying a string to another string without libraries like string.h 09-12-2015, 12:59 PM
#1
So I wrote this code, but after copying string 1 to string 2 it outputs extra characters depending on the size of my array and how many characters I put in my string.
My question is why?
With the current code, if I put a string of 8 characters to string 1 it outputs the string of string 2 (after string 1 is copied to string 2), with a 1 at the end, but everything copies fine with 9 characters or less except 8. Haven't tested it thoroughly, but if I minimize the array to 128 it just doesn't work right. Someone please explain.
My question is why?
Code:
#include <iostream>
using namespace std;
int main(){
char str_1[1000], str_2[1000];
cout << "Input String 1: "; cin >> str_1;
cout << "\nCopying string 1 to string 2....\n";
for(int i = 0; str_1[i] != '\0'; i++){
str_2[i] = str_1[i];
}
cout << "Value of string 2 is " << str_2 << endl;
return 0;
}With the current code, if I put a string of 8 characters to string 1 it outputs the string of string 2 (after string 1 is copied to string 2), with a 1 at the end, but everything copies fine with 9 characters or less except 8. Haven't tested it thoroughly, but if I minimize the array to 128 it just doesn't work right. Someone please explain.
![[Image: dHJ4Beo.gif]](http://i.imgur.com/dHJ4Beo.gif)
Hidden Lesson: Reactions are always instinctive whereas responses are always well thought of.












![[+]](https://sinister.li/images/modern/collapse_collapsed.png)


