用戶從控制檯輸入文章、計算文章中單詞個數並存入文件中


/*
 用戶從控制檯輸入一篇文章,輸入完成以後,判讀文章中一共有多少個單詞?
 char txt[2000];
 
 hello lili,hello hameimei,nice to meet you.
 hello nice to meet you too.

 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define  N  2000




void mystrcat(char * str1,char * str2)
{
    while (*str1!='\0') {
        str1++;
    }
    while (*str2!='\0') {
        *str1=*str2;
        str2++;
        str1++;
    }
    *str1='\0';
}


int main(int argc, const char * argv[])
{
    char txt[N];
    
    //提示用戶輸入文章
    printf("請輸入你的文章:");
    
    gets(txt);
    //printf("%s\n",txt);
    for (int j = 0; txt[j]!= '\0'; j++) {
        putchar(txt[j]);
    }
    
    printf("\n");
    
    int num = 0;//單詞個數
    int i = 0;
    while (txt[i] != '\0')
    {
        if (((txt[i]>=48&&txt[i]<=57)||(txt[i]>=65&&txt[i]<=90)||(txt[i]>=97&&txt[i]<=122))&&((txt[i+1]<48)||(txt[i+1]>57&&txt[i+1]<65)||(txt[i+1]>90&&txt[i+1]<97)||(txt[i+1]>122)))
        {
            num++;
        }
        i++;
    }
    
    printf("文章單詞個數爲%d\n",num);


    // 文件處理
    FILE *fp;
    char fileName[20];
    printf("請輸入文件名:");
    scanf("%s",fileName);
    
    char newname[] = {"//Users//haixia//Desktop//"};
    mystrcat(newname, fileName);
    
    //文件打開
    fp = fopen("//Users//haixia//Desktop//新建文件.txt", "w");
    rename("//Users//haixia//Desktop//新建文件.txt",newname);
    //寫入文件
    fprintf(fp, txt);
    //關閉文件
    fclose(fp);
  
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章