我的程序应该删除/**/注释,压缩空格,并删除输入的行拼接。
**编辑:向下滚动到下面的问题更新。
这是我的代码:
#include <stdio.h>
void ass(), f1(), f2(), f3();
int mainRunner();
int a, b;
int main() {
ass();
mainRunner();
}
void ass() {
a = getchar();
b = getchar();
}
int mainRunner() {
while ( a != EOF ) {
f1();
f2();
f3();
putchar(a);
a = b;
b = getchar();
}
}
// Removes Line Splices
void f1() {
if ((a == '\\') && (b == '\n')) {
a = getchar();
b = getchar();
mainRunner();
}
}
//Removes Comments in the /*...*/ form
void f2() {
if ((a == '/') && (b == '*')) {
while ((a != '*') || (b != '/')) {
a = b;
b = getchar();
}
a = getchar();
b = getchar();
mainRunner();
}
}
//Condenses White Spaces
void f3() {
if ((a == ' ') && (b == ' ')) {
a = b;
b = getchar();
mainRunner();
}
}
当我运行测试脚本(测试脚本 1)时:
a b c
d e
f
g
hifealkfja;efa faekjf;ale feafaefa
已返回
a b c
d e
f
g
hifealkfja;efa faekjf;ale feafaefa
????????????????
当我运行此测试脚本(测试脚本 2)时:
start linesplice NOW!\
This should be connected with first line.Comment begins here:/*fjelajfal;efjael$
fe;ajfe;fe8/Comment Ends.
Series of 5 spaces between the letters:a b
Series of 10 spaces between the letters:c d
Increasing number of spaces between letters from 1 space:e f g h i
没有任何反应,命令行光标移至最左侧。
感谢任何反馈,谢谢。 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~
问题更新: 通过执行 chux 建议的操作减少了上述问题。现在我只有问号问题。我做了修复,这样 putchars 就不会在堆栈中等待并在最后输出一大堆 EOF,但为什么仍然有两个问号?这是我的新代码:
#include <stdio.h>
void ass();
int mainRunner();
int a, b;
int main() {
ass();
mainRunner();
}
void ass() {
a = getchar();
b = getchar();
}
int mainRunner() {
while ( a != EOF ) {
// Removes Line Splices
if ((a == '\\') && (b == '\n')) {
a = getchar();
b = getchar();
mainRunner();
}
//Removes Comments in the /*...*/ form
if ((a == '/') && (b == '*')) {
while ((a != '*') || (b != '/')) {
a = b;
b = getchar();
}
a = getchar();
b = getchar();
mainRunner();
}
//Condenses White Spaces
if ((a == ' ') && (b == ' ')) {
a = b;
b = getchar();
mainRunner();
}
if (a == EOF) {
break;
}
else {
putchar(a);
a = b;
b = getchar();
}
}
}
当我运行上面的第二个测试脚本(添加星号以结束注释)时,我的程序输出:
start linesplice NOW!This should be connected with first line.Comment begins here:Comment Ends. Series of 5 spaces between the letters:a b Series of 10 spaces between the letters:c d Increasing number of spaces between letters from 1 space:e f g h i ??
注意最后的两个问号。 注意:该程序对于第一个测试脚本运行良好。
最佳答案
给定OP的第一个测试脚本:
f1()
中的 if
永远不会为 true。
f2()
中的 if
永远不会为 true。
f3()
通过 mainRunner()
有效地递归到自身。当看到EOF
时,递归停止并展开。 mainRunner()
在每次展开时执行 putchar(a);
,并在 a
中执行 EOF。
删除 f1()
、f2()
和 f3()
中的 mainRunner();
可能会帮助。
测试代码有 1 + 13 + 1 + 2 个 2 个空格的序列。这会导致 17 次递归调用。展开时,putchar(EOF)
被调用 16 次,创建 '?'
。
在OP的第二个测试脚本中。 f2()
进入无限循环
while ((a != '*') || (b != '/')) {
a = b;
b = getchar();
}
由于没有转义,getchar()
应该返回EOF
。
关于C 程序最后返回一系列问号,有时不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336553/