如何用 C 語言將完整的文字逐個單詞一行顯示?


首先,以寫入模式開啟檔案。然後,輸入文字,直到達到檔案結尾 (EOF),即按下 ctrlZ 關閉檔案。

再次以讀取模式開啟。然後,從檔案中讀取單詞,並分別在一行中列印每個單詞,然後關閉檔案。

我們實現的用一行列印一個單詞的邏輯如下 -

while ((ch=getc(fp))!=EOF){
   if(fp){
      char word[100];
      while(fscanf(fp,"%s",word)!=EOF) // read words from file{
         printf("%s
", word); // print each word on separate lines.       }       fclose(fp); // close file.    } }

示例

以下是顯示完整文字,一行一個單詞的 C 程式 -

 線上演示

#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("file.txt","w"); //open the file in write mode
   printf("enter the text then press cntrl Z:
");    while((ch = getchar())!=EOF){       putc(ch,fp);    }    fclose(fp);    fp=fopen("file.txt","r");    printf("text on the file:
");    while ((ch=getc(fp))!=EOF){       if(fp){          char word[100];          while(fscanf(fp,"%s",word)!=EOF) // read words from file{             printf("%s
", word); // print each word on separate lines.          }          fclose(fp); // close file.       }       Else{          printf("file doesnot exist");          // then tells the user that the file does not exist.       }    }    return 0; }

輸出

執行上述程式時,將產生以下結果 -

enter the text then press ctrl Z:
Hi Hello Welcome To My World
^Z
text on the file:
Hi
Hello
Welcome
To
My
World

更新於: 08-Mar-2021

1K+ 檢視

開始您的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.