gpt4 book ai didi

c - 每行打印 60 个字符

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:35 28 4
gpt4 key购买 nike

我编写了一个从用户那里获取文本文件的程序。

然后它应该一次打印 60 个字符,然后换行开始,然而,即使它有效

一些单词超过了这个限制然后它把单词切成两半然后开始

再次换行。所以我需要我的程序从根本上弄清楚

该词是否符合 60 个字符的限制,因此不会拆分任何词。

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char ch, file_name[25];
FILE *fp;
printf("Enter file name: \n");
scanf("%24s" ,file_name);

if ( (fp = fopen(file_name,"r")) == NULL ){
perror("This file does not exist\n");
exit(EXIT_FAILURE);}

int c, count;

count = 0;
while ( (c = fgetc(fp)) != EOF ) {
if ( c == '\n' )
putchar( ' ' );
else
putchar( c );

count++;
if ( count == 60 ) {
putchar( '\n' );
count = 0;
}
}
putchar( '\n' );
fclose(fp);
}

最佳答案

#include <stdio.h>
#include <stdlib.h>
int readWord(FILE *fp,char *buff,char *lastChar){
char c;
int n=-1;
*buff=0;
*lastChar=0;
while((c= fgetc(fp))!=EOF){
n++;
if(isspace(c)){
/*
you may keep tabs or replace them with spaces
*/
*lastChar=c;
break;
}
buff[n]=c;
buff[n+1]=0;
}
return n;
}


int main( void ) {
char ch, file_name[25];
char buff[50];
int pos=0;
FILE *fp;
printf("Enter file name: \n");
gets(file_name);

if ( !(fp = fopen(file_name,"r")) ) {
perror("This file does not exist\n");
exit(EXIT_FAILURE);
}

int c, count;

count = 0;
while ( (pos=readWord(fp,buff,&ch))!=EOF) {
count+=pos+(!!ch);
if(count>60){
printf("\n");
count=pos;
}

if(ch){
printf("%s%c",buff,ch);
}else{
printf("%s",buff);
}
if(!pos){
count=0;
}

}
putchar( '\n' );
fclose(fp);
return 0;
}

关于c - 每行打印 60 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594098/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com