1

As I understand that strings can be treated like arrays, so I tried to insert each character of a string by iterating with a while loop. However the final cout pointed to a memory address, not the string I hoped it would print.

int main()
{
    int i = 0;
    int n = 2;
    char input;
    string str1[n];
    
    while(i<=n){
        cout<<"enter letter: ";
        cin>>input;
        str1[i] = input;
        i++;
    }
    cout<<"Your word is: "<<str1;

    return 0;
}

The output was:

enter letter: a
enter letter: b
enter letter: c
Your word is: 0x7ffd505af1f0

How can I print my string at the end, instead of a pointer to a mem address?

More interestingly, when I adjusted the final line to cout str1[n] instead of str1, the console prints the next character in the alphabet from the last input!

cout<<"Your word is: "<<str1[n];

and the output is

enter letter: a
enter letter: b
enter letter: c
Your word is: d

How is this happening?

2 Answers2

3

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

Korosia
  • 593
  • 1
  • 5
  • 19
  • Thanks, I am making sense of this, a few points to take in. I didn't think about the .push_back, which I only came across once before in a dynamic array. Btw, when I run the c-string variant, the console says *** stack smashing detected ***: terminated – Kernel Bash Jan 11 '22 at 13:57
  • Also I don't understand this line 'cstr1[i] = n;' in the while loop. Wouldn't 'cstr1[i] = input;' ? – Kernel Bash Jan 11 '22 at 14:00
  • 1
    @KernelBash Woops, that will teach me to write code without running it! The stack smashing is because we were comparing against `i<=n`, not `i – Korosia Jan 11 '22 at 15:27
  • 2
    @user17732522 excellent point, I've edited accordingly. – Korosia Jan 11 '22 at 15:52
  • 1
    @KernelBash If you feel this answers your question, you can accept the answer by clicking the "tick" icon. – Korosia Jan 13 '22 at 10:17
1

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).

alagner
  • 3,448
  • 1
  • 13
  • 25
  • When I declare my var as 'string str1;' instead of 'string str1[n];' the console out is empty. I didn't think about how string str1[n] was an array of strings. – Kernel Bash Jan 11 '22 at 13:48
  • @KernelBash see the edited answer please. There are several ways to handle your problem, I've stated the two most obvious ones (to me at least), others involve e.g. preallocating the string and treating it as an array. See the [docs](https://en.cppreference.com/w/cpp/string/basic_string) for details – alagner Jan 11 '22 at 14:54