I was hoping that I could get some further explanation. I was told that I need to explicitly add \0 to the end of a string. Apparently this is for the C++ string class and that it is actually an array of characters that seems to be parsed under the hood. I was told that we must use the \0 in order to tell where the end of the string is as seen below:
int main() { char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << str << endl; return 0; } However, if I have a user input their name, for example, I don't believe that C++ automatically uses the \0 to terminate the string. So the argument that the \0 must be there to know where the string ends makes no sense. Why cant we use the .length() function to account for the length of the string?
I wrote the following program to illustrate that the length of the input can be found from the .length() function.
int main() { string firstName; cout << "Enter your first name: "; cin >> firstName; cout << "First Name = " << firstName << endl; cout << "String Length = " << firstName.length() << endl; return 0; } So, if the user inputs the name "Tom". Then the output would be the following:
First Name = Tom String Length = 3 I brought this to my professor's attention and also this article http://www.cplusplus.com/reference/string/string/length/ and I was told that is why I am in college because it cannot be done this way. Can any one offer any insight, since I don't understand what I am missing?
char[]and"quoted string literals"and thestringclass willy-nilly here. Please clarify your actual question. The purpose of the loop escapes me completely, as does what your output is supposed to mean.