Console couts a memory address instead of string
Solution 1:
When people say that strings are like arrays, they mean specifically "c-strings", which are just char arrays (char*
, or char []
). std::string
is a separate C++ class, and is not like an array. See this question for a definition of C-strings.
In your example, str1 is actually an array of std::strings, and when you print it, you're printing the pointer address.
Below is an example using both C++ std::string
, and a C-string, to illustrate the difference. In general, when writing C++, you should prefer std::string.
const int n = 2;
std::string str1; //A c++ std::string, which is not like an array
char cstr1[n+1]; // a c-string, which is array-like
for(int i = 0; i < n; ++i) {
char input = '\0';
cout<<"enter letter: ";
cin>>input;
str1.push_back(input); //Append to c++ string
cstr1[i] = input; //Add to array-like c-string
}
cstr1[n] = '\0'; //Ensure C-string is null-terminated
cout << "As C++: " << str1 << std::endl;
cout << "AS C: " << cstr1 << std::endl;
cout << "C++ can convert to C-string: " << str1.c_str() << std::endl;
Added const to n, to make it valid C++, since you shouldn't create arrays from non-const variables
Solution 2:
Most likely you meant either string str1;
or char str1[n];
(I suggest the first one, as the latter is a variable-length array supported only by compiler extensions, not a part of C++). string str1[n];
is an array of strings, which in generally decays to a pointer when passed around, so it happened in your case.
Should you decide to go with the std::string
I suggest getting rid of i
and n
and rewriting it to sth like that:
while(str1.size() < 2){
cout<<"enter letter: ";
cin>>input;
str1.push_back(input);
}
Should you decide to stick to C-style char array (char str1[n];
) I suggest making n
a compile time constant, i.e. by defining it the following way: constexpr int n = 5;
(provided you're on C++11 or newer).