【发布时间】:2014-01-23 10:15:37
【问题描述】:
所以我正在用 C 编写一个练习程序,其目的是获取用户输入,然后在达到 EOF 后,它会读回输入,但只读取超过 10 个字符的行。
我在 Linux 上,所以 EOF 是 Ctrl + D,但是,如果输入行长于 10 行,它会在我按 Enter 时打印,而不是等到 EOF 到达。
这是我的代码:
#define MAXSIZE 1000
#define SIZE 10
int checklen(char line[], int index);
int main()
{
char currentline[MAXSIZE];
int i = 0;
while ((currentline[i] = getchar()) != EOF){
if (currentline[i] == '\n'){
if (checklen(currentline, i) > SIZE){
printf("%s", currentline);
}
}
++i;
}
return 0;
}
int checklen(char line[], int index)
{
int i;
for (i=index; line[i] != '\n'; ++i){
;
}
return i;
}
编辑:我已经尝试了很长一段时间没有运气。我不太明白你们在说什么以及一切,但我们最终会到达那里:)
我已经重写了代码,但仍然无法正常工作。
#include <stdio.h>
#define MAX 1000
#define SIZE 10
void examine(char input[], int index);
int main()
{
int i=0;
char input[MAX];
char output[MAX];
//take user input and store it in our input string
while ((input[i] = getchar()) != EOF){
++i;
}
//put a null byte at the end of input[]
input[i+1] = '\0';
//examine line by line until end of string (null byte)
for (i=0; input[i] != '\0'; ++i){
if (input[i] == '\n'){
examine(input, i);
}
}
return 0;
}
void examine(char input[], int index)
{
//decrement through input[] until \n or start [0] is reached
int i=0;
for (i=0; ((input[index] != '\n') || (index > 0)); ++i){
--index;
}
//if line is bigger than 10 chars, print it
if (i>SIZE){
for (; input[index+1] != '\n'; ++index){
putchar(input[index]);
}
}
//otherwise, return
return;
}
【问题讨论】:
-
刚刚意识到这是因为我的 printf 在 if 语句中。现在我得想办法解决它......
-
EOF不是char,而是int! -
如果您真的不希望在输入完成之前出现任何输出,您将不得不在遇到换行符时保存每个有效(足够长)行,然后在阅读循环,您必须扫描已保存的行列表。随时生成输出更简单,更节省内存。
-
您的
checkline()代码也是错误的。仅当currentline[i]为换行符时才调用它;因此,在函数内部,您将i设置为index,循环条件立即失败,因此您返回您一开始就知道的index。您在调用代码中的条件可能是i > SIZE。另外,请注意:您没有以 null 结尾的字符串。这迟早会造成严重破坏。 -
这个问题不清楚,您正在尝试打印或仅接受超过
SIZE字符长度的行的输入(不清楚哪一行),但在您的代码中,看起来您只想要如果您有超过SIZE行,则打印您收到的所有行(无论大小)。请澄清。
标签: c string file-io input output