2011
1、文件读写:文件中每行存储一个字符串(数字),并以0作为结束。判断文件中的每个数字是否为水仙花数,并按照一定格式输出(✔)
/***读:
(1) fgets(buff,size,fp/stdin)
stdin表示从控制台读入到buff中
fp表示从文件中读入到buff
(2) fscanf(fp,format,buff)
format ="%[^\n]"表示读取一行
format ="%s" 表示读取字符串,且在遇到第一个空格时停止读
fgets与fscanf的区别在于fscanf在遇到第一个空格时会停止读写
写:
(1) fprintf(fp,"%s", buff)
(2) fputs(字符串,fp)
NOTE:
(1) atoi(char[]) 字符串转化为数字
(2) itoa()(int num,char[],radix) 数字转字符串,char[]为存储字符串的变量,radix为进制
**/
2、更完整版本
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[50][50];
int input(FILE *in,FILE *out);
void shui(FILE *out,int count);
void main()
{
FILE *in,*out;
int count;
if((in = fopen("shui.in","r")) == NULL)
{
printf("open file error!");
exit(0);
}
if((out = fopen("shui.out","w")) == NULL)
{
printf("open file error!");
exit(1);
}
count = input(in,out);
shui(out,count);
printf("写入成功!");
fclose(in);
fclose(out);
}
int input(FILE *in,FILE *out)
{
int i = 0,count = 0;
while(!feof(in))
{
fscanf(in,"%s",str[i]);
count++;
i++;
}
return count;
}
void shui(FILE *out,int count)
{
int a,b,i,n,sum = 0;
for(i = 0;i < count;i++)
{
n = atoi(str[i]);
a = n;
b = a % 10;
while(a)
{
sum += b*b*b;
a /= 10;
b = a % 10;
}
if(sum == n)
fprintf(out,"%s","T\n");
else
fprintf(out,"%s","F\n");
}
}