用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP