简体   繁体   中英

arrays of type char and rand function

I could not phrase the question properly but here it goes:
I want to create a random password and that password contains special characters,letter and numbers
so i have decided the ASCII range and assigned them to the password array everything works properly but when i print it out to the console weird characters pop up that were not in the range.

int main(){
    srand(time(nullptr));
    char password[15];
    int i = 0;
    for (i = 0; i < 15; i++)
    {
        password[i] = (rand() % 89) + 33;

    }
    cout << password << endl;
return 0;
}

that is the code that causes problem but when i assign the last element to be null value it works properly.
is it because when you create ac type string the last index should always be null?

A string must finish with a string terminator, or it isn't a string. If you omit the terminator, there is no way to know how long the string is. One might assume that since password is const char[15] that the size could be deduced, but in practice, just about everything that works with strings will treat it as a pointer and iterate until a null terminator is found. Since you don't have one, they will iterate past the end of your buffer leading to undefined behavior. Consider using std::string to avoid these concerns. See Null-terminated byte strings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM