USTC机试—按照字典索引顺序的建立,输出行号和单词

如:i am
      a student from

      china
输出:i 1

          am 1
          a 2

          student 2
          from 2

          china 3

/*#include<stdio.h>//此算法是重新对每一个单词按照字典顺序排序
#include<algorithm>
using namespace std;
#define N 100
struct store{//设计一个结构体重载小于符号,比较字典序
   char s[N];
   bool operator <(const store &a)const{
        return s[0]<a.s[0];
   }
}E[N];
int main(){
int count=0;//累计行数
FILE *fp1,*fp2;
fp1=fopen("4.in","r");
fp2=fopen("4.out","w");
while(!feof(fp1)){
    fscanf(fp1,"%s",E[count++].s);
}
sort(E,E+count);//结构体中已经重载了比较运算符,此处直接调用sort函数对字符串数组进行排序
for(int i=0;i<count;i++){
   fprintf(fp2,"%d %s\n",i,E[i].s);
}
return 0;
}*/
//此算法是重新按照行的顺序顺序输出行号和单词,此处用到fgets函数
#include<stdio.h>
#include<string.h>
#define N 100
int main(){
	char s[N];
	int count=0;
    FILE *fp1,*fp2;
	fp1=fopen("4.in","r");
	fp2=fopen("4.out","w");
	while(!feof(fp1)){
		count++;
		fgets(s,N,fp1);//此处注意fgets函数的参数格式以及其含义
		int len=strlen(s);
		fprintf(fp2,"%d ",count);//先提前输出每一行的行号
		for(int i=0;i<len;i++){
			if(s[i]!='\0'&&s[i]!=' '){
			fprintf(fp2,"%c",s[i]);
			}
			else{
			fprintf(fp2,"\n%d ",count);
			}
		}
	}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值