Click here to Skip to main content
15,743,541 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The error says string subscript out of range even though ive used std:: to further define strings in my program
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int main()
    cout << "Hello World!\n";
    string pass;
    for (int i = 0; i <= 8; i++) {
        pass = pass + data[rand() % 105];
    cout << "Your random password is " << pass << endl;


What I have tried:

ive tried removing some things the compiler may overreact to like unrecognizable characters
Updated 26-Jul-22 14:42pm

1 solution

Count the number of characters in data. There are 26 upper case letters, 26 lower case letters, 10 digits, and 26 other symbols, for a total of 88. You index data with a random value between 0 and 104. Sooner or later this ends up being a value of 88 or more, which is out of range for your data array. Try % 88 instead of % 105.

EDIT: It's actually 87, not 88, because you left out 'n'!
Share this answer
k5054 26-Jul-22 21:31pm    
Better yet, rather than manually counting the number of chars in the string, just use the length() member of string.
pass += data[ rand() % data.length() ];
CPallini 27-Jul-22 1:58am    
Greg Utas 27-Jul-22 5:53am    
Definitely better.
CPallini 27-Jul-22 1:58am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900