一次阅读每个角色 - C

时间:2016-10-13 01:39:14

标签: c getchar

对于以下question

  

练习12336 - 从程序的标准输入一次读取一个字符的普通文本,并用从左到右反转的每一行打印它。阅读,直到遇到数据结束`

     

您可能希望通过键入“

来测试程序
      prog5rev | prog5rev
     

查看是否重新创建了原始输入的精确副本。要读取字符到数据结尾,请使用循环,例如“

   char ch;
   while( ch = getchar(), ch >= 0 ) /* ch < 0 indicates end-of-data */
    or
    char ch;
    while( scanf( "%c", &ch ) == 1 ) /* one character read */

这是我的解决方案:

#include  <stdio.h>

void f(char *);
int main(void)
{
    char ch = getchar();
    f(&ch);

    return 0;
}

void f(char *ch){
    if(*ch < 0)
        return;
    else{
        char character = getchar();
        f(&character);
    }
    putchar(*ch);
}

输入:

abc | abc

输出:

cba | cba

问题:

问题是:print it with each line reversed from left to right.

此解决方案是否正确?

3 个答案:

答案 0 :(得分:1)

这是一个非常聪明的解决方案,我真的不想打破它,但使用堆栈有一些限制。内存限制准确。如果你有超过一定的,相对少量的输入,它将达到极限并以某种方式崩溃,例如:分段错误。来自古腾堡的完整莎士比亚的所有5,560,737个字符都没有通过,它在654,337字符处被分段。

您需要使用堆来获取更大的输入,抱歉。

答案 1 :(得分:0)

是的,这可以按预期工作。

你读了一个角色并打电话给f。如果未读取EOF,请再次调用f,然后打印读取的字符。因为在递归调用之后打印字符,所以字符以相反的顺序打印。

然而,您应该进行的一项更改是使用int而不是char作为数据类型。 getchar函数返回int,以便可以正确检测到EOF。 putchar函数接受int,因此您无需为此担心。

此外,由于调用函数没有更改它,因此无需传递已读入的变量的地址。您可以简单地传递变量的值并相应地更改函数。

答案 2 :(得分:-1)

问题的陈述已经提示了解决方案:

   char ch;
   while( ch = getchar(), ch >= 0 ) /* ch < 0 indicates end-of-data */
    or
    char ch;
    while( scanf( "%c", &ch ) == 1 ) /* one character read */

您必须使用循环从stdin读取数据,然后在循环内部测试是否有新行,然后,只有这样,从右到左打印该行(还原字符串)。

以下是以简单方式编写任务的代码,它可能需要一些改进,但它可以工作。

请阅读评论并尝试了解其中的内容,如果您有任何疑问,请咨询他们。

#include <stdio.h>
#include <string.h> // for memset

void f(char *, int);

int main(void)
{
    char ch;
    char buffer[1024] = { 0 }; // 1024 = max supported line length
    int i; // ieterator

    i = 0;
    while( scanf( "%c", &ch ) == 1 ) { // while there is input
        if ( ch == '\n' ) { // if there is a new line
            f(buffer, i); // print the line (inverted)
            i = 0; // reset iterator
            memset(buffer, 0, 1024); // reset buffer
        } else {
            buffer[i++] = ch; // append read char to the buffer
        }
    }

    return 0;
}

void f(char *str, int n) {
    // just print from right to left (easier than reversing and then printing the string)
    while (n >= 0) {
        putchar(str[n]);
        n--;
    }
    putchar('\n');
}

更新:本书建议使用

测试程序
 prog5rev | prog5rev

我建议创建一个输入文件,然后运行:

 $ prog5rev < input.txt | prog5rev

之前的声明假设您正在使用linux(或某些unix)。

示例:

[ichramm@wilderjager][~]$ cat input.txt 
hello
world
[ichramm@wilderjager][~]$ ./test < input.txt  
olleh
dlrow
[ichramm@wilderjager][~]$ ./test < input.txt | ./test 
hello
world