c输入输出到文件

我这个定义的是c++程序

输入

前面那个单词统计题

#include <iostream>
#include <map>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>//必须引用
#include <algorithm>

using namespace std;

int main()
{
    FILE *fp;
    map<string,int> maps;
    vector<string> vec;
    char ch[30];
    maps.clear();
    vec.clear();
    fp=fopen("e:\\a.txt","r");  /*假设a.txt在e盘根目录下,r是只读*/
	if(!fp)exit(0);
    while(fscanf(fp,"%s",ch)!=EOF)//输入有所不同
    {
        int len=strlen(ch);
        for(int i=0; i<len; i++)
        {
            ch[i]=towlower(ch[i]);
        }
        maps[ch]++;
        if(maps[ch]==3)
        {
            vec.push_back(ch);
        }
    }
    fclose(fp);//关闭流
    sort(vec.begin(),vec.end());
    for(int i=0; i<vec.size()&&i<10; i++)
    {
        printf("%s\n",vec[i].data());
    }
    return 0;
}


输出

将30000以内的素数写入到a.txt中

#include <iostream>
#include <math.h>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>//必须引用
using namespace std;

int main()
{
    int i;
    int temp;
    FILE *fp;//定义一个文件指针
    fp=fopen("E:\\a.txt","w");//以只写的方式打开文件,前面的参数是文件路径,后面的参数是表示只写
    if(fp==NULL){//文件不存在,则结束
        exit(0);
    }
    else{
	    for (i=2; i<=30000; ++i)
	    {
	        int q=sqrt(i);
	        temp=0;
	        for(int j=2; j<=q; j++)
	        {
	            if (i%j==0)
	            {
	                temp=1;
	                break;
	            }
	        }
	        if(temp==0)
	        {
	            fprintf(fp,"%d,", i);//将结果输出到文件中
	          //  printf("%d ",i);//将结果输出到控制台
	        }
	    }
 	}
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值