looping & generating strings by user input

I want to generate 3 strings, however, I'm having a problem generating a loop based on the user input of how many times 3 random strings should be generated into an HTML file.

the output, as well as the format, would be as follows if the user wants to generate 3 strings 4 times and output an HTML file for example :

1
2
3
4
5
6
random string is :psp
random string is :sfs
random string is :asda
random string is :daf

Random HTML File has been generated!




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
#include<fstream>
#include <string>
#include <cstdlib>
#include <ctime>


using namespace std;
    static const char alphanum[] =
    "abcdefghijklmnopqrstuvwxyz";
    int stringLength = sizeof(alphanum) - 1;



    char genRandom()
{

    return alphanum[rand() % stringLength];
}


int main(){
   const int STRING_CHAR_CHOICE = 1,
             TIMES_CHOICE = 2,
             QUIT_CHOICE = 4;

   // Display the menu and get a choice.
   cout << "\t\t STRING GENRATOR \n\n";
   cout << "1. Choose how many strings\n";
   cout << "4. Quit the Program\n\n";
   cout << "Enter your choice: ";
   cin >> choice;


int choice;       // To hold a menu choice
int stringTimes;       // To hold a number of strings the user want to generate
int timez;       // To hold the number of times the user want to generate the loop

   cout << "How many strings would you like to generate random strings: ";
   
   cin >> choice;
      // Set the numeric ouput formatting.
   cout << fixed << showpoint << setprecision(2);

   // Respond to the user's menu selection.
   if (choice == STRING_CHAR_CHOICE)
   {
      cout << "How many strings you want to generate in each loop? ";
      cout << "How many times you want to generate random strings? ";
      cin >> stringTimes;
    rand(time(0));
    std::string Str;
while (unsigned int i = 0; i < timez; ++i)
    for(unsigned int i = 0; i < stringTimes ; ++i)

      
   }
   else if (choice == QUIT_CHOICE)
   {
       cout << "Program ending.\n";
   }
   else
   {
      cout << "The valid choices are 1 through 2. Run the\n";
      cout << "program again and select one of those.\n";
   }


    ofstream outFile;
    //path variable to store the path of file
    string path = "random.html";
    //file is opened with given path
    outFile.open(path);

    //check whether file is opened successfully or not
    if(!outFile.is_open()){
        cout<<"\nFile not opened correctly.";
    }



        
    {

         //declared a number variable to store random numbers
        Str += genRandom();

    }
    cout <<"random string is :"<<  Str << endl;



        //inserting numbers in file
        outFile<<Str<<"\n";
    }
    //closing file
    outFile.close();
    //printing desired output
    cout<<"\nRandom html File has been generated!";
    return 0;
}



This would show when running the c++ file and would be stored in an HTML file I have successfully been able to generate the 3 strings but I'm not able to loop of how many times the user wants this to be. I also want to make sure that the SAME random 3 strings don't generate again but that above my knowledge I'm still learning c++ .
Last edited on
What are you classifying as 'random string'? Up to how many chars are allowed in each string?

How many strings would you like to generate random strings:


This makes no sense.

Could you explain more clearly what you are trying in accomplish?

Do you want to generate a group of 3 strings a specified number of times? Generating 3 strings 4 times could be:


random string is :psp
random string is :sfs
random string is :asda

random string is :daf
random string is :psd
random string is :cfs

random string is :asfda
random string is :daf
random string is :psp

random string is :sfs
random string is :asdz
random string is :dgf


Is this what you mean?


???????
Hello Leonardo797,

Watch your indenting it is terrible. Proper indenting and blank lines make it easier to read.

When I put your program in VS2017 it is full of errors like:
32
33
34
35
36
cout << "Enter your choice: ";
cin >> choice;


int choice;       // To hold a menu choice 

You can not use "choice" in line 33 and then define the variable on line 36.

53
54
while (unsigned int i = 0; i < timez; ++i)
        for (unsigned int i = 0; i < stringTimes; ++i)

Should line 53 be a while or a for loop? It looks like it should be a for loop.

83
84
85
86
87
88
{

    //declared a number variable to store random numbers
    Str += genRandom();

}

This creates a block which is not necessary Also "Str" appears to be undefined.

In line 76 when the if statement is true you print an error message. That is fine, but why do you continue with the program if the file did not open? End the if block with "return 1;".

In line 18 you use "rand" correctly, but in line 51 you have it wrong. "rand()" takes no parameters.

Also you should put: srand(static_cast<size_t>(time(nullptr))); near the top of main to seed the RNG before you use it.

Andy

Edit: If you want to use cout << fixed << showpoint << setprecision(2); you will need the header file "iomanip".
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <set>
using namespace std;

int main()
{
   srand( time( 0 ) );
   int STRING_LENGTH = 3, NUMBER_OF_STRINGS = 4;
   set<string> allStrings;
   while( allStrings.size() < NUMBER_OF_STRINGS )
   {
      string s;
      for ( int i = 0; i < STRING_LENGTH; i++ ) s+= 'a' + rand() % 26;
      allStrings.insert( s );
   }
   
   cout << "Your (non-duplicated) strings are:\n";
   for ( string s : allStrings ) cout << s << '\n';
}


As a matter of interest, why do you want the output to go to an html file? This output manifestly isn't html.
Last edited on
Hello Leonardo797,

Along with what seeplus has asked it would help if you would show exactly what the output should look like. This is what you want the program TO DO not so much what it does.

Trying to keep with what you started with I came up with this as a start:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

//static const char alphanum[] =
//"abcdefghijklmnopqrstuvwxyz";
const std::string alphanum{ "abcdefghijklmnopqrstuvwxyz" };
const size_t stringLength = alphanum.size();

char genRandom()
{
    return alphanum[rand() % stringLength];
}

int main()
{
    constexpr int STRING_CHAR_CHOICE = 1,  // <--- Needs to be made a constant
        TIMES_CHOICE = 2,
        QUIT_CHOICE = 4;
    int choice{};       // To hold a menu choice
    int numOfStrings{};  // <--- Added. Not sure how to use it yet.

    srand(static_cast<unsigned int>(time(nullptr)));  // <--- Needs done once near the beginning.

    // Set the numeric output formatting.
    cout << fixed << showpoint << setprecision(2);  // <--- Needs header file "iomanip".

    // Display the menu and get a choice.
    cout<<
        "\t\t STRING GENERATOR \n\n"  // <--- Changed spelling.
        "1. Choose how many strings\n"
        "4. Quit the Program\n\n"
        " Enter your choice: ";
    cin >> choice;

    cout << "\nHow many strings would you like to generate random strings: ";
    cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.

    std::string Str;  // <--- Moved.
    int stringTimes{};       // To hold a number of strings the user want to generate
    int timez{};       // To hold the number of times the user want to generate the loop.  

This is good down to line 42, but lines 42 and 43 need to be somewhere else. But I am not sure yet how to use it.

You use "choice" for the menu selection, but line 43 overwrites the menu selection with something else before you have the opportunity to use "choice" for the if/else if statements. Not a good way to do this.

I moved this definition of std::string Str; to line 44 because you have it defined inside an if block. The problem with this is when the if block loosed scope the variable is destroyed, so when you try to use it later, which BTW is in the wrong place, "Str" is undefined.

Andy
Hello everyone, Thanks for all of your efforts, I appreciate everything. Let me make this more clear also this is for seeplus, what I want is to let the user choose how many chars to be generated

so if it's 3 it would be :

1
2
random string is :gfd

if its 4 it would be :vsdv

1
2
random string is :dsfs

if its 8 it would be :
1
2

random string is :yrhkosbn

then i want to to let the user generate the strings more than once so it would be what seeplus said but without spaces, if the user wants 3 strings 12 times it would be :

1
2
3
4
5
6
7
8
9
10
11
12
random string is :psp
random string is :sfs
random string is :asd
random string is :daf
random string is :psd
random string is :cfs
random string is :asfd
random string is :daf
random string is :psp
random string is :sfs
random string is :asd
random string is :dgf

notice each string is 3 chars because the user input was 3 but also generated 12 times

that's it
Last edited on
Yes, but why do random strings in your example output consist of 4 or 5 characters and most others consist of 3 characters?

And your example output doesn't look all that random. Maybe you should state your assignment, not some weird interpretation of it.

And why do you want to put it in an html file?
Last edited on
also Andy, thanks for the effort,


                 STRING GENERATOR

1. Choose how many strings
4. Quit the Program

 Enter your choice: 1

How many strings would you like to generate random strings: 3

Process returned 0 (0x0)   execution time : 16.725 s
Press any key to continue.




you got the idea, but after
How many strings would you like to generate random strings: 3
it should ask the user want's to generate then dump the results to .html file, like
how many times ? the user input 12 the results are


1
2
3
4
5
6
7
8
9
10
11
12
random string is :psp
random string is :sfs
random string is :asd
random string is :daf
random string is :psd
random string is :cfs
random string is :asf
random string is :daf
random string is :psp
random string is :sfs
random string is :asd
random string is :dgf


this is not for homework it's just for me I'm curious if c++ is able to do that.
Last edited on
Hello Leonardo797,

Working with what you have I came up with this:

The screen output is:
STRING GENRATOR

1. Choose how many strings
4. Quit the Program

Enter your choice: 1

How many strings would you like to generate?: 10
How long do you want the strings? 5

random string is: ixdzf
random string is: hzuzo
random string is: jgykc
random string is: dnotm
random string is: vesle
random string is: artfc
random string is: fouly
random string is: jgifx
random string is: pkdlr
random string is: mdgxz


Random text File has been generated!


Based on the 2 questions I used 2 for loops to generate the output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if (choice == STRING_CHAR_CHOICE)
{        
    cout << "\nHow many strings would you like to generate?: ";
    cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.
                          // This applied before I moved it here where it belongs.

    cout << "How long do you want the strings? ";
    cin >> lengthOfString;

    std::cout << '\n';

        for (int numStrings = 0; numStrings < numOfStrings; numStrings++)
        {
            for (int strLen = 0; strLen < lengthOfString; ++strLen)
            {
                Str += genRandom();
            }

            std::cout << "random string is: " << Str << '\n';

            //inserting strings into the file.
            outFile << Str << '\n';

            Str.clear();  // <--- Clears the string "Str" before the next loop.
        }
}


This gives the output file (random.txt) this:
ixdzf
hzuzo
jgykc
dnotm
vesle
artfc
fouly
jgifx
pkdlr
mdgxz


If you want the part "random string is: " it is easy to add.

lastchance wrote:

And your example output doesn't look all that random.



One reason for this is the way you are using "rand()" and its drawbacks. See
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
About a 30 minute video, but very useful information. There is also
https://web.archive.org/web/20180123103235/http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/

lastchance used s+= 'a' + rand() % 26; which works a little better, but can still produce duplicates as in the output above. Sometimes it is better with less duplicates.


Andy

Edit: You are creating a text file not a html file.
Last edited on
Hello Leonardo797,


this is not for homework it's just for me I'm curious if c++ is able to do that.



Yes it can.

I use a C++ program to create a html file.

First it reads a "txt" file that contains the opening html code and prints it to an output file.

Next the program reads a "CSV" file created by Excel and creates a html table.

Ending with reading a "txt" file that contains the ending html code. It finishes up by creating some Java script to make some changes in the html code.

When I open the html file in my browser it looks 98% like the original Excel file.

Also Python and Ruby on Rails are 2 languages that come to mind that could be used.

Andy

Edit: typo
Last edited on
Thanks for the effort and the videos, everything is helpful, but I'm confused about the last code

I get |54|error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'const size_t' {aka 'const long long unsigned int'})|"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

//static const char alphanum[] =
//"abcdefghijklmnopqrstuvwxyz";
const std::string alphanum{ "abcdefghijklmnopqrstuvwxyz" };
const size_t lengthOfString = alphanum.size();

char genRandom()
{
    return alphanum[rand() % lengthOfString];
}

int main()
{
    constexpr int STRING_CHAR_CHOICE = 1,  // <--- Needs to be made a constant
        TIMES_CHOICE = 2,
        QUIT_CHOICE = 4;
    int choice{};       // To hold a menu choice
    int numOfStrings{};  // <--- Added. Not sure how to use it yet.

    srand(static_cast<unsigned int>(time(nullptr)));  // <--- Needs done once near the beginning.

    // Set the numeric output formatting.
    cout << fixed << showpoint << setprecision(2);  // <--- Needs header file "iomanip".

    // Display the menu and get a choice.
    cout<<
        "\t\t STRING GENERATOR \n\n"  // <--- Changed spelling.
        "1. Choose how many strings\n"
        "4. Quit the Program\n\n"
        " Enter your choice: ";
    cin >> choice;

    cout << "\nHow many strings would you like to generate random strings: ";
    cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.

    std::string Str;  // <--- Moved.
    int stringTimes{};       // To hold a number of strings the user want to generate
    int timez{};       // To hold the number of times the user want to generate the loop.
    if (choice == STRING_CHAR_CHOICE)
{
    cout << "\nHow many strings would you like to generate?: ";
    cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.
                          // This applied before I moved it here where it belongs.

    cout << "How long do you want the strings? ";
    cin >> lengthOfString;

    std::cout << '\n';

        for (int numStrings = 0; numStrings < numOfStrings; numStrings++)
        {
            for (int strLen = 0; strLen < lengthOfString; ++strLen)
            {
                Str += genRandom();
            }

            std::cout << "random string is: " << Str << '\n';

            //inserting strings into the file.
            outFile << Str << '\n';

            Str.clear();  // <--- Clears the string "Str" before the next loop.
        }
}


     return 0;
}

I added your first code with the last one, please if you still have the code paste it so I can see
Hello Leonardo797,

Line 54 is: cin >> lengthOfString;, but where is "lengthOfString" defined?

You have defined
1
2
int stringTimes{};       // To hold a number of strings the user want to generate
int timez{};       // To hold the number of times the user want to generate the loop. 

Which are never used and I changed these names for a better understanding later.

In your code you have:
1
2
3
4
5
6
7
8
9
10
11
12
13
    cout<<
        "\t\t STRING GENERATOR \n\n"  // <--- Changed spelling.
        "1. Choose how many strings\n"
        "4. Quit the Program\n\n"
        " Enter your choice: ";
    cin >> choice;

    cout << "\nHow many strings would you like to generate random strings: ";
    cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.

    std::string Str;  // <--- Moved.
    int stringTimes{};       // To hold a number of strings the user want to generate
    int timez{};       // To hold the number of times the user want to generate the loop. 

Defining your variables is fine, but lines 8 and 9 are done before they are needed, and eventually I removed them completely from the program and changed the first prompt inside the if statement.

Line 31 is never used or is needed.

The code I have come up with is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

//static const char alphanum[] =
//"abcdefghijklmnopqrstuvwxyz";

//const std::string alphanum{ "abcdefghijklmnopqrstuvwxyz" };  // <--- Just a different way to define the variables.
//const size_t stringLength = alphanum.size();

char genRandom()
{
    return 'a' + rand() % 26;  // <--- This eliminates the above constant variables.
}

int main()
{
    constexpr int STRING_CHAR_CHOICE = 1,  // <--- Needs to be made a constant
        TIMES_CHOICE = 2,
        QUIT_CHOICE = 4;
    int choice{};       // To hold a menu choice
    int numOfStrings{};  // <--- Added. Not sure how to use it yet.

    ofstream outFile;

    //path variable to store the path of file.  No path involved here.
    string fileName = "random.txt";  // <--- This is a file name not a path. Should also be ".txt" not ".html".

    //file is opened with given path
    outFile.open(fileName);

    //check whether file is opened successfully or not
    if (!outFile)  // <--- All you need.
    {
        cout << "\nFile not opened correctly.";

        return 1;
    }

    srand(static_cast<unsigned int>(time(nullptr)));

    // Set the numeric ouput formatting.
    //cout << fixed << showpoint << setprecision(2);  // <--- Needs header file "iomanip". Actually not needed in the first place.

    // Display the menu and get a choice.
    cout<<
        "\t\t STRING GENRATOR \n\n"
        "1. Choose how many strings\n"
        "4. Quit the Program\n\n"
        " Enter your choice: ";
    cin >> choice;

    std::string Str;
    int lengthOfString{};       // To hold a number of strings the user want to generate
    int numOfSets{};       // To hold the number of times the user want to generate the loop. 

    // Respond to the user's menu selection.
    if (choice == STRING_CHAR_CHOICE)
    {
        //cout << "\nHow many sets would you like to generate? ";
        //std::cin >> numOfSets;
        
        cout << "\nHow many strings would you like to generate?: ";
        cin >> numOfStrings;  // <--- Would change the value of "choice", so your menu choice may not be usable.

        cout << "How long do you want the strings? ";
        cin >> lengthOfString;

        std::cout << '\n';

        for (int numStrings = 0; numStrings < numOfStrings; numStrings++)
        {
            for (int strLen = 0; strLen < lengthOfString; ++strLen)
            {
                Str += genRandom();
            }

            std::cout << "random string is: " << Str << '\n';

            //inserting strings into the file.
            outFile << Str << '\n';

            Str.clear();  // <--- Clears the string "Str" before the next loop.
        }
    }
    else if (choice == QUIT_CHOICE)
    {
        cout << "\n\n     Program ending.\n";

        return 0;
    }
    else
    {
        cout << "The valid choices are 1 through 2. Run the\n";
        cout << "program again and select one of those.\n";
    }

    //closing file
    outFile.close();  // <--- Not necessary. Will close when "main" looses scope. OK to leave.

    //printing desired output
    cout << "\nRandom text File has been generated!";

    return 0;
}

In the line static const char alphanum[] = "abcdefghijklmnopqrstuvwxyz";
"ststic" is not needed ad a global is always there. Using "static" has no advantage with a global variable.

If you need a path to your output file you could do something like this:
1
2
3
4
5
6
7
8
//path variable to store the path of file.  No path involved here.
const std::string PATH{ "C:/something/something/" };
const std::string fileName = "random.txt";  // <--- This is a file name not a path. Should also be ".txt" not ".html".

//file is opened with given path
outFile.open(PATH + fileName);
// Or
//ofstream outFile(PATH + fileName); 


Andy
Hi Andy I really want to thank you for your explanation and hardwork, thanks so much you have solved my issue, I still don't know why I can't use html and add '\n' to make them look like a text file, if I change the file from txt to html it goes horizontal instead of vertical , I guess that's because it requires more work to let c++ know it's HTML formating,anyways I learned something new thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
Last edited on
Hello Leonardo797,

Try changing line 86 to outFile << Str << "<br>" << '\n';. That should give you something to start with. You could leave the output file name as a ".txt" extension or change it to a "html" extension.

If you want more in the "html" file we can work on that.

Andy
Topic archived. No new replies allowed.