1
我可以反轉數組,但是我無法讓程序在終端執行CTRL + D(EOF)時終止。
我可以讓程序終止的唯一方法是如果編譯後我做的第一件事是做CTRL + D。但是如果我輸入一個字符串,那麼在此之後CTRL + D將不起作用。K&R練習1-19:反向字符數組
我不太確定我的錯誤在哪裏。
#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;
}
我能想到的唯一的事情是在主要檢查while循環如果len> 0,所以如果我鍵入EOF,也許它不能進行有效的比較?但是,當這是我輸入的第一個也是唯一的東西時,它爲什麼會起作用沒有任何意義。
你不是在Windows上運行你的程序,是嗎? – dasblinkenlight
@ user3121023你是對的,它就這麼簡單。我很尷尬,我沒有嘗試做幾次。謝謝。 – boy
您不初始化'newL',所以如果您的讀取循環沒有以換行符結束,您的程序會顯示未定義的行爲。 – rici