使用c++编写程序 生成文本文件data.txt,文件内容是10个手机号码(手机号码前4位为1871,后面随机生成)
时间: 2023-06-05 14:05:38 浏览: 89
好的,这是一个编程问题,我可以回答。以下是生成data.txt文件的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
FILE *fp;
char filename[] = "data.txt"; // 文件名
int i;
srand(time(NULL)); // 初始化随机数发生器
fp = fopen(filename, "w"); // 打开文件,以写入方式
// 生成10个手机号码写入文件中
for (i = 0; i < 10; i++) {
char phone[12];
sprintf(phone, "1871%d%04d", rand() % 10000, rand() % 10000); // 生成手机号码
fprintf(fp, "%s\n", phone); // 写入文件
}
fclose(fp); // 关闭文件
return 0;
}
```
将上述代码保存为test.c,然后执行下列命令编译并运行:
```
gcc -o test test.c
./test
```
执行成功后,会在当前目录下生成一个名为data.txt的文件,其中包含10个手机号码。
相关问题
编程生成文本文件data.txt,文件内容是10个手机号码(手机号码前4位为1871,后面随机生成)(尝试用多种方式实现,至少2种方式)
好的,以下是两种实现方式:
方式一:使用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个手机号码。
使用C++编写程序,从键盘输入10个整数,并存入文本文件data.txt中
好的,以下是使用C++编写的程序,可以从键盘输入10个整数,并将其存入文本文件data.txt中:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int nums[10];
// 从键盘输入10个整数
cout << "请输入10个整数:";
for (int i = 0; i < 10; i++) {
cin >> nums[i];
}
// 将数据保存到文件中
ofstream outfile("data.txt");
if (outfile.is_open()) {
for (int i = 0; i < 10; i++) {
outfile << nums[i] << " ";
}
outfile.close();
cout << "数据已保存到文件data.txt中" << endl;
}
else {
cout << "打开文件失败!" << endl;
}
return 0;
}
```
这个程序会依次从键盘输入10个整数,然后将这些整数以空格为分隔符保存到data.txt文件中。如果文件打开失败,则会输出相应的提示信息。