A standard programmer often needs to perform comprehensive tests on the software modules he has written. In a sense, Every programmer should be responsible for the Code he has written.
In testing, we must use a large amount of test data. The following applet completes this function. You can specify the type, length, number of records, and final output file name of the string to be generated in the main program. // Random. cpp: generate a random string (a combination of pure numbers, pure letters, or numbers and letters ),
// Save the generated string to a text file
// Author: Fang xinmiao
// Email: smecf@163.com
// Date: 2008.05.11
# Include <iostream>
# Include <vector>
# Include <time. h>
# Include <list>
# Include <string>
# Include <stdlib. h>
# Include <fstream>
Using namespace STD;
/*
* Function: generate a random number within the specified range.
* Parameter: irange-random number range
* Return value: the random number generated.
*/
Int gennum (const int irange)
{
Return (RAND () % irange );
}
/*
* Function: generate a string consisting of pure numbers with a specified number of digits.
* Parameter: ilength-String Length
* Return value: random string
*/
String gennumofstring (const int ilength)
{
String STR = "";
Char ch [2];
For (INT I = 0; I <ilength; I ++)
{
_ Itoa_s (gennum (10), CH, 2, 10 );
STR + = CH;
}
Return STR;
}
/*
* Function: generate a string (97 ~ 122)
* Parameter: ilength-String Length
* Return value: random string
*/
String genletterofstring (const int ilength)
{
String STR = "";
For (INT I = 0; I <ilength; I ++)
STR + = (char) ('A' + gennum (26 ));
Return STR;
}
/*
* Function: generate a string consisting of digits and letters with a specified number of digits (random digits and letters)
* Parameter: ilength-String Length
* Return value: random string
*/
String genmixedstring (const int ilength)
{
String STR = "";
For (INT I = 0; I <ilength; I ++)
{
If (gennum (2 ))
STR + = gennumofstring (1); // Add a numeric character
Else
STR + = genletterofstring (1); // Add a letter
}
Return STR;
}
/*
* Function: saves the strings in the linked list to a file.
* Parameter: lst-string linked list, strfilename-file name
* Return value: void
*/
Void exporttofile (const list <string> & lst, const string & strfilename)
{
Ofstream out;
Out. Open (strfilename. c_str (), ios_base: APP );
If (! Out)
Cerr <"the specified file name is invalid! "<Endl;
List <string >:: const_iterator ITER;
For (iter = lst. Begin (); iter! = Lst. End (); ITER ++)
Out <* ITER <Endl;
Out. Close ();
}
// The following main program only provides a call example that generates 2000 groups, each group contains 10 characters, digits, and English letters.
Int main ()
{
Srand (unsigned) Time (null); // random number generator
List <string> lst;
List <string >:: iterator ITER;
For (INT I = 0; I <2000; I ++)
Lst. push_back (genmixedstring (10 ));
String STR = "data.txt ";
Exporttofile (LST, STR );
Return 0;
}