我正在制作一個“身份生成器”,計算機從 .txt 檔案中隨機選擇行。
雖然它適用于代碼的第一部分,但當我重復該代碼并更改變數時,它仍然使用舊的 txt 檔案。
預期結果:
Full name: {random first name} {random sur name}
Address: {random address}
實際結果:
Full name: {random first name} {random first name}
Address: {random first name}
我的代碼
cout << "Full name: ";
srand((unsigned) time(NULL));
std::ifstream firstnamefile("englishfirstname.txt");
int total_lines = 0;
while(getline(firstnamefile,line))
{
total_lines ;
lines.push_back(line);
}
int random_number = rand() % total_lines;
cout << lines[random_number] << " ";
//--- Surname ---
srand((unsigned) time(NULL));
std::ifstream surnamefile("englishsurname.txt");
total_lines = 0;
while(getline(surnamefile,line))
{
total_lines ;
lines.push_back(line);
}
random_number = rand() % total_lines;
cout << lines[random_number] << endl;
// --- Address ---
cout << "Address: ";
srand((unsigned) time(NULL));
std::ifstream addressfile("addresses.txt");
total_lines = 0;
while(getline(addressfile,line))
{
total_lines ;
lines.push_back(line);
}
random_number = rand() % total_lines;
cout << lines[random_number] << endl;
.txt 檔案只是名稱串列,例如:
John
Michael
Matthew
Etc...
uj5u.com熱心網友回復:
您永遠不會 clear lines,因此向量的開頭始終是您的名字串列。在讀取每個檔案之前,您確實重置total_lines為 0,因此您的隨機范圍是0..total_lines每次,所以您總是從陣列的開頭選擇,這也是所有名字。
假設 lines 是 a std::vector,您需要lines.clear()設定total_lines為 0 來重置每個檔案讀取之間的狀態。
請注意,您有三個相同的代碼塊,它們僅在檔案名上有所不同;對于接受檔案作為輸入并回傳隨機行作為輸出的函式來說,這是一個非常好的候選者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521611.html
標籤:C 文件随机的文本
上一篇:當glDraw*Instanced()呼叫的primcount大于頂點屬性可以更新的次數時會發生什么?
下一篇:在C 中使用串列向量構建紅黑樹
