C&C++常用小函数 代码

格式化输入输出文件

#include "stdafx.h" #include <stdlib.h> #include "string.h" #include "stdio.h" int main() { FILE *fp; int number[3]; int score[3]; int i = 0; int rece_Number = 0; if((fp = fopen("test.txt","r")) == NULL) { fprintf(stderr,"Error opening file!/n"); } for(i =0;i<3;i++) { fscanf(fp,"%d %d",&number[i],&score[i]);//学号与成绩用空格 } printf("Please input number:/n"); scanf("%d",&rece_Number); for(i = 0;i<3;i++) { if(rece_Number == number[i]) break; } printf("The Number's score is %d/n",score[i]); fclose(fp); return 0; }  

统计字符串中最长的重复字符串

#include "stdafx.h" #include "string.h" #include "malloc.h" int main() { int i,j,k,t; int max = 0; char *p = NULL; char str[42] = "2xtuaojy5678zuaojy908puaojy417uaojy356"; char temp[8]; char result[8]; memset(result,0,8); p = str; for(i=0;i <42;i++) { for(j=i+1;j <42;j++) { if(*(p+i)== *(p+j)) { t = i; k = 0; memset(temp,0,8); //只要找到了相同的首字符,就开始比较直到没有相同的字符,记录当前字符串,看是否是最长的 while(*(p+t)== *(p+j)) { temp[k] = *(p+t);//不断比较后续的字符 t++; j++; k++; } if(k > max)//将最长的字符串赋值给result { max = strlen(temp); strcpy(result,temp); } } } } //打印出结果在上述字符串中最长的是 "zuaojy" printf("重复字符串最长的是 %s,长度为 %d /n",result,max); return 0; } 

 

通过递归求字符串中出现的相同字符次数

int count_times(char ch,const char* str) { int count = 0; if(*str == '/0') { count = 0; } else { if((*str)==ch) { count = 1+count_times(ch,str+1); } else { count = count_times(ch,str+1); } } return count; } 

你可能感兴趣的:(C++,c,File,null,input,FP)