用c++编写:读取文件nameList中候选人名单,随机抽取三位候选人作为获奖者,将获奖人信息输出到屏幕上同时保存到文件winner.txt。不使用vector
时间: 2023-06-27 11:07:23 浏览: 50
以下是一个简单的 C++ 程序,可实现读取文件 nameList 中的候选人名单,随机抽取三位候选人作为获奖者,将获奖人信息输出到屏幕上同时保存到文件 winner.txt。本程序不使用 vector。
```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
// 打开文件 nameList
ifstream infile("nameList.txt");
if (!infile.is_open())
{
cout << "无法打开文件 nameList.txt" << endl;
return 1;
}
// 读取候选人名单
string name;
int count = 0;
string names[100];
while (getline(infile, name))
{
names[count++] = name;
}
// 关闭文件 nameList
infile.close();
// 随机抽取三个获奖者
srand(time(0));
int winners[3];
for (int i = 0; i < 3; i++)
{
winners[i] = rand() % count;
}
// 输出获奖者信息到屏幕和文件
ofstream outfile("winner.txt");
if (!outfile.is_open())
{
cout << "无法打开文件 winner.txt" << endl;
return 1;
}
for (int i = 0; i < 3; i++)
{
cout << "获奖者 #" << i + 1 << ": " << names[winners[i]] << endl;
outfile << "获奖者 #" << i + 1 << ": " << names[winners[i]] << endl;
}
// 关闭文件 winner.txt
outfile.close();
return 0;
}
```
该程序首先打开文件 nameList.txt,读取候选人名单,将名单存储在字符串数组 names 中。接着,使用 srand 和 rand 函数随机抽取三个获奖者,将他们的信息输出到屏幕和文件 winner.txt 中。注意,在输出信息到文件时,需要使用 ofstream 类型对象 outfile,将信息写入文件并关闭文件。