2014-11-03 52 views
0

是否可以打印用户输入而不使用字符数组?不使用字符数组打印输入

#include<stdio.h> 
main() 
{  
    int ch; 
    while((ch = getchar()) != EOF){ 
      putchar(ch); 
    } 
} 

例如,我要进入:

当输入字符参与此代码不能正常工作

abcd 
efgh 
ij 

,我想输出是相同的:

abcd 
efgh 
ij 

但是当我输入第一行时,程序也应该输出该行(在我的输入之后)。它是这样的:

abcd (my input) 
abcd (output) 
efgh (my input) 
efgh (output) 
ij (my input) 
ij (output) 
+6

无法根据给定条件获得预期输出! – haccks 2014-11-03 19:15:39

+0

haccks说,你必须重新考虑你的算法 – 2014-11-03 19:17:11

+0

你能澄清你的要求吗?当你说'输入三行输入'时,你的意思是你运行你的程序并在标准输入中输入三行?你希望你的程序能够回显数据,但是:你想只看到一个数据副本,还是希望看到两个数据副本,一个在另一个之前,或者你想看到交错输入和输出线?如果输入从文件重定向而不是从键盘输入,您希望发生什么?你是在类Unix的机器上,还是在Windows上,或者其他的东西(因为有些建议可能需要POSIX)? – 2014-11-03 21:16:06

回答

1
#include<stdio.h> 

int main(){ 
    FILE *fp = fopen("echo.tmp", "w+"); 
    int ch; 
    while((ch = getchar()) != EOF){ 
     fputc(ch, fp); 
    } 
    fflush(fp); 
    rewind(fp); 
    while((ch = fgetc(fp)) != EOF){ 
     putchar(ch); 
    } 
    fclose(fp); 
    remove("echo.tmp"); 
    return 0; 
} 
1

为了好玩,不切实际的递归解决方案。

阅读char后,将它放在堆栈上并递归。

完成后(EOF),通过堆栈递归。

#include <stdio.h> 

typedef struct prev_T { 
    struct prev_T *prev; 
    int ch; 
} prev_T; 

void put1(prev_T *s) { 
    if (s != NULL) { 
    // Swap this line and the next if you want to print in reverse. 
    put1(s->prev); 
    putc(s->ch, stdout); 
    } 
} 

void get1(prev_T *s) { 
    prev_T node; 
    node.ch = getchar(); 
    if (node.ch == EOF) { 
    put1(s); 
    } else { 
    node.prev = s; 
    get1(&node); 
    } 
} 

    int main(void) { 
    get1(NULL); 
    return 0; 
    } 
0

一个更不切实际的递归解决方案:

#include <stdio.h> 
#include <stdarg.h> 

void unwind(va_list ap) 
{ 
    int ch = va_arg(ap, int); 
    if (ch == EOF) 
     return; 

    va_list a2 = va_arg(ap, va_list); 
    va_end(ap); 
    unwind(a2); 
    putchar(ch); 
} 

void package(int dummy, ...) 
{ 
    va_list ap; 
    va_start(ap, dummy); 

    int ch = getchar(); 
    if (ch == EOF) 
     unwind(ap); 
    else 
     package(0, ch, ap); 
} 

int main() 
{ 
    package(0, EOF); 
} 
+0

你甚至可以让'dummy'成为某种输入参数,例如。最大长度 – 2014-11-04 01:24:57

0

简单的,非递归,非常实用,从你给输入完成你想要的输出方法是读单个字符并立即输出,对特殊字符进行特殊处理。例如,您可以测试字符值13,以在按下回车键时输出换行符,并查找其他特殊字符来表示输入结束。