由于某些原因,我的提示无法正常工作。我认为这与需要刷新的缓冲区有关。读取文件后,我尝试添加一个cout << flush
,但这并不能解决问题。我打印的唯一位置是for循环中的main()
。这是我从那些照片获得的输出。
Aeberg
Aaren
Aaron
Full Name
Aaron
在亚伦前后,都有一个空格。因此只打印姓氏。
#include <iostream>
#include <fstream>
#include <queue>
#include <time.h>
using namespace std;
const int SIZE = 50000;
void initFirst(string first[]);
void initMiddle(string middle[]);
void initLast(string last[]);
int main()
{
srand(time(NULL));
ifstream in;
ofstream out;
string first[SIZE];
string middle[SIZE];
string last[SIZE];
initFirst(first);
initMiddle(middle);
initLast(last);
string x;
for(int i = 0; i < 1; i++)
{
cout << first[i] << endl;
cout << middle[i] << endl;
cout << last[i] << endl;
cout << "Full Name" << endl;
cout << first[i] << " " << middle[i] << " " << last[i] << endl; // Isn't printing correctly here
}
return 1;
}
void
initFirst(string first[])
{
ifstream file("names.txt");
string line;
int counter = 0;
if(file.is_open())
{
while(getline(file, line))
{
first[counter] = line;
counter++;
}
file.close();
}
int left = SIZE - counter;
int random[left];
for(int i = 0; i < left; i++)
random[i] = rand() % counter;
for(int i = counter; i < SIZE; i++)
first[i] = first[random[i-counter]];
}
void
initMiddle(string middle[])
{
ifstream file("first-names.txt");
string line;
int counter = 0;
if(file.is_open())
{
while(getline(file, line))
{
middle[counter] = line;
counter++;
}
file.close();
}
int left = SIZE - counter;
int random[left];
for(int i = 0; i < left; i++)
random[i] = rand() % counter;
for(int i = counter; i < SIZE; i++)
middle[i] = middle[random[i-counter]];
}
void
initLast(string last[])
{
ifstream file("middle-names.txt");
string line;
int counter = 0;
if(file.is_open())
{
while(getline(file, line))
{
last[counter] = line;
counter++;
}
file.close();
}
int left = SIZE - counter;
int random[left];
for(int i = 0; i < left; i++)
random[i] = rand() % counter;
for(int i = counter; i < SIZE; i++)
last[i] = last[random[i-counter]];
}
答案 0 :(得分:1)
我建议稍微改善一下您的程序。
init
,一个就足够了。只需传递文件名参数即可。string first[SIZE]
-这会导致堆栈溢出。改用向量。int random[left];
random
数组#include <cstdint>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <time.h>
const size_t SIZE = 50000;
using strings = std::vector<std::string>; // 'array' of strings with dynamic size
void initFromFile(const std::string &fname, strings &arr)
{
std::ifstream file(fname);
std::string line;
while(getline(file, line))
arr.push_back(line);
size_t n = arr.size();
if(n == 0)
return;
for(auto i = 0; i < SIZE-n; i++)
arr.push_back(arr[rand() % n]);
}
int main()
{
using std::cout;
using std::endl;
srand(time(NULL));
strings first, middle, last;
initFromFile("names.txt", first);
initFromFile("first-names.txt", middle);
initFromFile("middle-names.txt", last);
for(auto i = 0U; i < first.size(); i++)
{
cout << first[i] << endl << middle[i] << endl << last[i] << endl;
cout << "Full Name" << endl;
cout << first[i] << " " << middle[i] << " " << last[i] << endl;
}
}