【发布时间】:2016-12-03 06:26:04
【问题描述】:
我有一个包含 4 个段落的文本文件 (input.txt),我必须将这些段落的句子一个接一个地写在另一个文件 (output.txt) 中(用换行符分隔)。
原文件中的句子用'.'、'!'分隔和'?'。
我已经完成了,但我的代码有问题。 output.txt文件中有些句子没有换行
我的代码:
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break;
}
c_next = fgetc(fp);
if( feof(fp) ) {
fprintf(fp_output, "%c", c);
break;
} else {
if( c=='.' || c=='?' || c=='!' ) {
fprintf(fp_output, "%c\n", c);
} else {
if( c=='\n' ) {
fprintf(fp_output, "%c", c_next);
} else if( c_next=='\n' ) {
fprintf(fp_output, "%c ", c);
} else {
fprintf(fp_output, "%c%c", c, c_next);
}
}
}
}
例如,对于输入文件:
This is the first sentence. The second one contains some more words, other words,
more words, etc. The third sentence has; and more like: this, that, those.
This is the second paragraph. And now a question? Only an exclamative
sentence is missing!
This is the third paragraph. Another component - word - would be this.
The final sentence of the paragraph!
This is the last paragraph.
我的代码得到以下输出:
This is the first sentence.
The second one contains some more words, other words, more words, etc. The third sentence has; and more like: this, that, those.
This is the second paragraph.
And now a question?
Only an exclamative sentence is missing!
This is the third paragraph. Another component - word - would be this.The final sentence of the paragraph!
This is the last paragraph.
问题出在第二行和第六行。每行最多1句。
欢迎任何想法、提示或解决方案。
谢谢
【问题讨论】:
-
考虑如果
c_next是句号('.'),您的代码会做什么。调试此类问题的方法是使用调试器逐行遍历代码。您对c和c_next的使用只会导致混淆。我建议你可以不用c_next。 -
没有 c_next 怎么办?我如何知道新句子何时开始? @kaylum 或者只是检查字符是否为大写?
-
好吧,如果有一个句号,那就告诉你句子已经结束了。为什么你需要句号后的下一个字符才能知道句子是否在那里结束?下一个字符无关紧要。句号本身就足够了。
-
@kaylum 我试着按照你告诉我的方式去做,但我做不到。如果您能向我展示代码,我将不胜感激。谢谢
标签: c