我编写了一个从用户那里获取文本文件的程序。
然后它应该一次打印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);
}
答案 0 :(得分:2)
#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;
}
答案 1 :(得分:1)
您可以扫描一个单词,如果行和单词小于60,则连接它们。否则,打印该行并将该单词复制到开始重复处理的行。
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = NULL;
char file_name[257] = {'\0'};
char line[61] = {'\0'};
char word[61] = {'\0'};
int out = 0;
printf ( "Enter file name:\n");
scanf ( " %256[^\n]", file_name);
if ( ( fp = fopen ( file_name, "r")) == NULL) {
printf ( "could not open file\n");
return 1;
}
while ( ( fscanf ( fp, "%60s", word)) == 1) {
if ( strlen ( line) + strlen ( word) + 1 <= 60) {
strcat ( line, " ");
strcat ( line, word);
out = 0;
}
else {
printf ( "%s\n", line);
strcpy ( line, word);
out = 1;
}
}
if ( !out) {
printf ( "%s\n", line);
}
fclose ( fp);
return 0;
}