Originally Posted by
tabstop
1. I have no idea what it's trying to print. There's probably some sort of conversion going on.
2. Since you're supposed to take the loop out, that's pretty irrelevant.
3. Yes. The \0 character always goes at the end of the input. It would be really bad for your string to be "Jackson Heightsßßßßßßßßßßßßßßßßßßßßßßßß".
Hi tabstop
Please comment on the embedded comment in the code below. Thanks.
Code:
// strcopy1.cpp
// copies a string using a for loop
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
const int MAX = 80;
int i;
char str1[] = "Oh, Captain, my Captain! "
"\nOur fearful trip is done";
/*
A C-String could be initialized in two ways:
1: char str[] = "hello world";
2: char str[] = {'h','e','l','l','o',' ', 'w','o','r','l','d','\0'};
Just leave the square brackets empty []
*/
char str2[MAX];
for(i=0; i<strlen(str1); i++)
{
str2[i] = str1[i];
}
/*
Although NULL terminator would be inserted automatically
but only after 79 elements have been entered.
If str1 was 20 elements long, then (79 - 20) elements would
contain garbage values. Therefore, one has to enter NULL
explicitly.
*/
str2[i] = '\0';
cout << str2 << endl;
system("pause");
return 0;
}