在main函数中创建一个文件,将键盘输入的字符串(该字符串只包含数字、字母和)写入文件中。打开该文件,读出字符串。将字符串中的数字放到最前面,字母放到中间,号放到最后,并将形成的新串存放到另一个文件中。比如,aC12d3,经变换为,123aCd**。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// swap two characters
void swap(char *a, char *b)
{
char t = *a;
*a = *b;
*b = t;
}
// return the category of the character
int category(char a)
{
if (isdigit(a))
return 0;
else if (isalpha(a))
return 1;
else
return 2;
}
// compare two characters according to categories
int compare(char a, char b)
{
return category(a) - category(b);
}
// bubble sort
void sort(char str[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (compare(str[j], str[j + 1]) > 0)
swap(&str[j], &str[j + 1]);
}
}
}
int main()
{
char buffer[255];
FILE *file = fopen("file1.txt", "w");
if (!file)
{
perror("failed to open file1.txt");
return 1;
}
scanf("%s", buffer);
fprintf(file, "%s", buffer);
fclose(file);
file = fopen("file1.txt", "r");
if (!file)
{
perror("failed to open file1.txt");
return 2;
}
fscanf(file, "%s", buffer);
fclose(file);
sort(buffer, strlen(buffer));
file = fopen("file2.txt", "w");
if (!file)
{
perror("failed to open file2.txt");
return 3;
}
fprintf(file, "%s", buffer);
fclose(file);
return 0;
}
解答如下
把代码文件和text.txt文件放在同一目录下即可
#include <stdio.h>
#include <string.h>
void swap()
{
char t[150];
FILE* fp;
fp=fopen("text.txt","r");
if(fp==NULL)
{
printf("文件打开失败!\n");
return;
}
else
{
fscanf(fp,"%s",t);
printf("%s\n",t);
}
fclose(fp);
int n=strlen(t);
int num=0;
for(int i=0;i<n;i++)
{
if(t[i]<='9'&&t[i]>='0')
{
char tem=t[i];
for(int j=i;j>num;j--)
{
t[j]=t[j-1];
}
t[num]=tem;
num++;
}
}
printf("%s\n",t);
FILE* fp2;
fp2=fopen("text-2.txt","w");
if(fp2==NULL)
{
printf("文件打开失败!\n");
return;
}
else
{
fprintf(fp,"%s\n");
}
fclose(fp2);
}
int main()
{
FILE* fp;
swap();
return 0;
}
你看一下你贴的文字,有些*号都看不到了,把内容放到代码块吧
#include <stdio.h>
#include <stdlib.h>
#inclue <string.h>
int main()
{
FILE *fp1 = fopen("D:\\file1.dat","w");
FILE *fp2 = NULL;
FILE *fp3 = NULL;
int i=0;
int m1=0,m2=0,m3=0;
char s[1000] = {0};
char s1[1000] = {0};
char s2[1000] = {0};
char a1[1000] = {0},a2[1000] = {0},a3[1000] = {0};
if(fp1 == NULL)
{
printf("file1 open error !");
return 1;
}
scanf("%s",s);
fwrite(s,1,strlen(s),fp1);
fclose(fp1);
//
fp2 = fopen("D:\\file1.dat","r");
fread(s1,1,1000,fp2);
fclose(fp2);
while(s1[i] != '\0')
{
if(s1[i] == '*')
a3[m3++] = s1[i];
else if(s1[i] >='0' && s1[i] <='9')
a1[m1++] = s1[i];
else
a2[m2++] = s1[i];
i++;
}
strcpy(s2,a1);
strcpy(s2+strlen(a1),a2);
strcpy(s2+strlen(a1)+strlen(a2),a3);
//
fp3 = fopen("D:\\file2.dat","w");
if(fp3 == NULL)
{
printf("file2 open error !");
return 1;
}
fwrite(s2,1,strlen(s2),fp3);
fclose(fp3);
return 0;
}