该程序提示用户输入名称。然后它将使用两个while循环。一个while循环生成3个随机字母,然后是一个破折号,后跟另一个while循环生成3个随机数字。我可以根据需要让程序执行三次。
问题是它将为输入的三个名称中的每一个生成相同的三个随机数字和字母。我希望输入的每个名字都能打印出一组独特的字母和数字。它与srand()函数有关吗?
在输入第二个名称后打印字符后添加破折号以及打印输入的第三个名称的字符后两个破折号也存在问题。
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int nameCount = 0; // Hold the number of names entered by user
string randomID; // Used to concatenate the random ID for 3 names
string name; // To hold the 3 names entered by the user
int numberOfCharacters = 0;
int numberOfNumbers = 0;
int a;
srand(time(NULL));
while(nameCount < 3) {
cout << "\nEnter a name: ";
getline(cin, name);
while (numberOfCharacters < 3) {
randomID += static_cast<int>('a') + rand() %
(static_cast<int>('z') - static_cast<int>('a') + 1);
numberOfCharacters++;
}
randomID += "-";
while (numberOfNumbers < 3) {
randomID += static_cast<int>('1') + rand() %
(static_cast<int>('1') - static_cast<int>('9') + 1);
numberOfNumbers++;
}
cout << randomID;
nameCount++;
}
return 0;
}
你使randomID
为空,将numberOfCharacters
设置为零,并在循环外只将numberOfNumbers
设置为零。相反,这样做:
int main() {
int nameCount = 0; // Hold the number of names entered by user
string name; // To hold the 3 names entered by the user
int a;
srand(time(NULL));
while(nameCount < 3) {
string randomID; // Used to concatenate the random ID for 3 names
int numberOfCharacters = 0;
int numberOfNumbers = 0;
cout << "\nEnter a name: ";
...
也:
randomID += static_cast<int>('1') + rand() %
(static_cast<int>('1') - static_cast<int>('9') + 1);
我不认为一减九就是你想要的。尝试交换1和9。