用 C 語言編寫一個程式來使用函式和迴圈處理語句


問題

如何在程式中根據指定長度將長行列印成兩行或多行短行(使用 C 語言)?

解決方案

讓我們編寫一段程式碼來讀取長行,並根據程式中提到的指定大小將其列印成兩行或多行短行。

我們在本程式中用到的內建函式 readline() 函式,用於將文字儲存到陣列並返回行的長度。

我們用來讀取短句的邏輯如下所述 −

while((charcter=readtext())>0){
   if(charcter>length){
      count=0;
      a=0;
      while(a<charcter){
         if(msg[a]==' ')
            b=a;
         if(count==length){
            msg[b]='
';             count=0;          }          count++;          a++;       }    }    printf("%s",msg); }

我們用來讀取長句的邏輯如下所述 −

for(i=0;i<MAX-1 && (charcter=getchar())!=EOF && charcter!='
';i++) msg[i]=charcter; if(charcter='
'){    msg[i]=charcter;    ++i; } msg[i]='\0'; return i;

程式

以下是透過使用函式和迴圈對語句進行處理的 C 語言程式 −

#include<stdio.h>
#define MAX 100
int readtext(void);
char msg[MAX];
const int length=30;
int main(){
   int a,b,count,charcter;
   printf("enter the statement:
");    while((charcter=readtext())>0){       if(charcter>length){          count=0;          a=0;          while(a<charcter){             if(msg[a]==' ')                b=a;             if(count==length){                msg[b]='
';                count=0;             }             count++;             a++;          }       }       printf("%s",msg);    }    return 0; } int readtext(void){    extern char msg[];    int charcter,i;    for(i=0;i<MAX-1 && (charcter=getchar())!=EOF && charcter!='
';i++)       msg[i]=charcter;       if(charcter='
'){          msg[i]=charcter;          ++i;       }       msg[i]='\0';    return i; }

輸出

輸出如下所示 −

enter the statement:
Hi Welcome to TutorialsPoint .It is one of the biggest platform where you can find all types of study materials with a very good and validate content,students can get there solutions in this platform
Hi Welcome to TutorialsPoint
.It is one of the biggest
platform where you can find all
types of study
materials with a very good
and validate content,students
can get there solutions in
this platform

更新時間: 2021-03-10

101 次瀏覽

開啟您的 職業

完成本課程,獲取認證

開始學習
廣告
© . All rights reserved.