0
Why can't I use string here instead of char array?
#include<iostream> #include<cstdlib> #include<ctime> using namespace std; void password(){ srand(time(0)); string chars = "Ab124*&"; char pass[10]; for (int i = 0; i < 10; i++) pass[i] = chars[rand()%7]; cout << pass; } main(){ password(); } In the above code, I've used 'char pass[10]' as a character array. Instead, if I declare 'string pass' or 'string pass = "\0" ', the code doesn't work. But if I initialise the string to any other random value for example, 'string pass = "45in4tnwri" ', then the code works. Why is it so?
1 Odpowiedź
+ 9
When you do
string pass;
without initializing anything, you cannot use it as an array because no size is specified explicitly or implicitly. If you want to use string, do it as such:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
void password(){
srand(time(0));
string chars = "Ab124*&";
string pass;
for (int i = 0; i < 10; i++)
pass += chars[rand()%7];
cout << pass;
}
int main(){
password();
}