【发布时间】:2016-12-28 09:48:36
【问题描述】:
我可以很好地反转数组,但是当我在终端中执行 CTRL+D(EOF) 时,我无法让程序终止。
我可以让程序终止的唯一方法是,如果我在编译后做的第一件事是执行 CTRL+D。但是如果我输入一个字符串,那之后 CTRL+D 就不起作用了。
我不太确定我的错误在哪里。
#include <stdio.h>
#define MAXLINE 1000 // Maximum input.
// ----------------- reverseLine -----------------
// This method reads in chars to be put into an
// array to make a string. EOF and \n are the
// delimiters on the chars, then \0 is the
// delimiter for the string itself. Then the
// array is swapped in place to give the reverse
// of the string.
//------------------------------------------------
int reverseLine(char s[], int lim)
{
int c, i, newL;
// c is the individual chars, and i is for indices of the array.
for (i = 0; i < lim - 1 && (c=getchar()) != EOF && c != '\n'; ++i)
{
s[i] = c;
}
if (c == '\n') // This lets me know if the text ended in a new line.
{
newL = 1;
}
// REVERSE
int toSwap;
int end = i-1;
int begin = 0;
while(begin <= end) // Swap the array in place starting from both ends.
{
toSwap = s[begin];
s[begin] = s[end];
s[end] = toSwap;
--end;
++begin;
}
if (newL == 1) // Add the new line if it's there.
{
s[i] = '\n';
++i;
}
s[i] = '\0'; // Terminate the string.
return i;
}
int main()
{
int len;
char line[MAXLINE];
while ((len = reverseLine(line, MAXLINE)) > 0) // If len is zero, then there is no line to recored.
{
printf("%s", line);
}
return 0;
}
我唯一能想到的是 main 中的 while 循环检查是否 len > 0,所以如果我输入 EOF,可能无法进行有效比较?但是,当这是我输入的第一个也是唯一一个内容时,为什么它会起作用是没有意义的。
【问题讨论】:
-
你没有在 Windows 上运行你的程序,是吗?
-
@user3121023 没错,就是这么简单。我很尴尬,我没有尝试过几次。谢谢。
-
你没有初始化
newL,所以如果你的读取循环没有以换行符终止,你的程序就会表现出未定义的行为。