gpt4 book ai didi

c - 如何实现格式化功能

转载 作者:行者123 更新时间:2023-11-30 15:15:27 25 4
gpt4 key购买 nike

首先,我试图在我的代码中实现格式化功能

我读取了用户输入的文本文件以及格式化功能

此文本文件中包含诸如“.br”、“.sp”和“.ce”。

所以我试图做一个 if 语句,如果程序找到单词“.br”它

应该立即中断并开始新行的下一个单词,但我真的

想不出办法来做到这一点。

#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 ( "This file does not exist.\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 ((word) == ".br"){

}
}
if ( !out) {
printf ( "%s\n", line);
}

fclose ( fp);
return 0;
}

我为“.br”功能创建了 IF 语句,但我确实需要帮助或一些

提示实际要放入循环中的内容。

最佳答案

添加 if 条件以将单词与“.br”进行比较。打印出当前行并将 line 设置为接受空字符串中的下一个单词。

#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 ( strcmp ( word, ".br") == 0) {
printf ( "%s\n", line);
line[0] = '\0';
out = 1;
}
else 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;
}

关于c - 如何实现格式化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33613776/

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