-4

I am new at the c++. I made basic random string program but I cant print the string to console. These are my codes :

enter image description here

vsync
  • 118,978
  • 58
  • 307
  • 400
  • 6
    Do not post your code as image. Please post your code as text directly in your question. Also note that functions must be declared or defined before being used. – MikeCAT Jun 28 '20 at 08:06
  • Please paste your code and apply markdown syntax instead of a code-screenshot next time :) – vsync Jun 28 '20 at 08:07
  • `#include ` is missing. – PaulMcKenzie Jun 28 '20 at 08:08
  • 1
    There are many issues in your code. For example it should be `string& line`. Even better, the string should be returned by the function. Moreover, the size of `line` is not defined. So you have out-of-bound access with `line[i]` – Damien Jun 28 '20 at 08:11
  • Your case is wrong: 1. You are using a copy inside your randomString function, not reference; 2. You are using [] operator but your string is empty. So it is UB. – Amir Kadyrov Jun 28 '20 at 08:11
  • `line[i] = character;` should be `line += character;` – MikeCAT Jun 28 '20 at 08:13

1 Answers1

1

you did not include <string> and also you take the string by copy, to edit it you'll have to pass it by reference using &

#include <string>
void randomString(std::string& line)

you don't need to assign a number to int and then assign it to char, char is an integer value in c++ so you can:

char character = rand()%122 + 97;

with this method your random numbers will not be very good, you can look into How to generate a random number in C++?

you access your string with [] operator and it has not yet been defined, to add a character to a string just use

line += character;

also if you want a random number length, there is no need for the boolean and i++ stuff:

int charNumb = rand() % 8 + 4;
while(charNumb--)

will do just fine and it looks much cleaner.

SzymonO
  • 432
  • 3
  • 15