编程生成文本文件data.txt,文件内容是10个手机号码(手机号码前4位为1871,后面随机生成)(尝试用多种方式实现,至少2种方式)
时间: 2024-03-08 18:47:58 浏览: 57
好的,以下是两种实现方式:
方式一:使用ofstream流写入文件
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
ofstream outfile("data.txt");
srand(time(NULL)); // 设置随机数种子
for (int i = 0; i < 10; i++) {
outfile << "1871" << rand() % 100000000 << endl; // 生成手机号码
}
outfile.close(); // 关闭文件
return 0;
}
```
方式二:使用cstdio库函数写入文件
```c++
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
FILE *pFile = fopen("data.txt", "w");
srand(time(NULL)); // 设置随机数种子
for (int i = 0; i < 10; i++) {
fprintf(pFile, "1871%d\n", rand() % 100000000); // 生成手机号码
}
fclose(pFile); // 关闭文件
return 0;
}
```
以上两种方式均可实现生成文本文件data.txt,文件内容为10个手机号码。