0

I'm new to programming , when I cout << str outside the loop , it prints nothing and when cout << str[0] << str[1] it prints the char in this position and also length of str outside of the loop is 0, what is the reason for that behavior.

Note: I tried to use concatenate str+= s[i]; and it's working in this case , I can cout << str;

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int n,k;
    cin >> n >> k;
    int z = k;
    string s = "abcdefghijklmnopqrstuvwxyz";
    string str;
    int repeated = n-k;
    for(int i{};i<n;++i){
        if(k > 0){      //distinct
        str[i] = s[i];
            k--;
            //cout << str[i];
        }else if(k==0 && repeated >0){    //repeated
            str[i] = str[i-z];
            repeated--;
            //cout << str[i];
        }
    }
    cout << str;
        //cout << str[0] << str[1] << str[2] << str[3] << str[4] ;
    return 0;
}

1 Answer 1

2

string str; is an empty string with size 0 and nothing in your code changes that.

Accessing any element but str[0] invokes undefined behavior. There is no str[i] for i > 0.

To append to a string you can use + or std::string::append.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer , this means accessing any element in str doesn't change it's size and i have to append.
@logan_92 exactly. std::map and std::unordered_maps operator[] is a weird exception, but other than that I don't know any standard container that implicity grows its size on element access, you either have to resize or push_back or append or +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.