通过getchar和putchar打印多行

时间:2013-07-18 07:59:33

标签: c input output getchar putchar

我是初学者,学习C编程语言并使用Microsoft Visual C ++编写和测试代码。

C文件中的程序(第1.5.1节)下面的程序通过putchar()和getchar()将其输入复制到其输出:

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

每次按ENTER键时,键盘输入程序打印字符。因此,我只能在打印前输入一行。在打印之前,我找不到通过键盘输入多行文本的方法。

有没有办法以及如何让这个程序从键盘输入和输出多行文字?

对不起,如果这是一个基本的,无知的问题。

提前感谢您的关注和感谢。

4 个答案:

答案 0 :(得分:1)

巧妙地使用指针算法来做你想做的事:

#include <stdio.h>  /* this is for printf and fgets */
#include <string.h> /* this is for strcpy and strlen */
#define SIZE 255 /* using something like SIZE is nicer than just magic numbers */

int main()
{
    char input_buffer[SIZE];        /* this will take user input */
    char output_buffer[SIZE * 4];   /* as we will be storing multiple lines let's make this big enough */

    int offset = 0; /* we will be storing the input at different offsets in the output buffer */

    /* NULL is for error checking, if user enters only a new line, input is terminated */
    while(fgets(input_buffer, SIZE, stdin) != NULL && input_buffer[0] != '\n') 
    {
        strcpy(output_buffer + offset, input_buffer); /* copy input at offset into output */
        offset += strlen(input_buffer);               /* advance the offset by the length of the string */
    }

    printf("%s", output_buffer); /* print our input */

    return 0;
}

这就是我使用它的方式:

$ ./a.out 
adas
asdasdsa
adsa

adas
asdasdsa
adsa

一切都是鹦鹉学舌:)

我使用了fgetsstrcpystrlen。请查看它们,因为它们是非常有用的功能(并且fgets是建议的用户输入方式。)

答案 1 :(得分:0)

此时只要输入“+”并按下输入,您输入的所有数据都将打印出来。您可以将数组的大小增加到100以上

#include <stdio.h>
    int main(void)
    {   int c='\0';
         char ch[100];
         int i=0;
        while (c != EOF){
          c = getchar();
          ch[i]=c;
      i++;

            if(c=='+'){

            for(int j=0;j<i;j++){
                printf("%c",ch[j]);
            }
        }
    }
        return 0;


    }

您可以在'+'字符或任何您想要表示打印操作的字符上添加条件,以便此字符不会存储在数组中(我现在没有在'+'上添加任何此类条件)

答案 2 :(得分:0)

使用setbuffer()使stdout完全缓冲(最大为缓冲区的大小)。

#include <stdio.h>
#define BUFSIZE 8192
#define LINES 3
char buf[BUFSIZE];
int main(void)
{   int c;
    int lines = 0;
    setbuffer(stdout, buf, sizeof(buf));
    while ((c = getchar()) != EOF) {
         lines += (c == '\n');
         putchar(c);
         if (lines == LINES) {
              fflush(stdout);
              lines = 0;
         }}
    return 0;}

答案 3 :(得分:-1)

您可以使用GetKeyState函数检查按住Enter键时是否按住SHIFT键吗?那就是你可以使用SHIFT / ENTER输入多行,并使用普通的ENTER键发送整个行。类似的东西:

#include <stdio.h>
int main(void)
{    int c;
     while (true){
         c = getChar();
         if (c == EOF && GetKeyState(VK_LSHIFT) {
              putchar("\n");
              continue;
         else if(c == EOF) break;
         else {
              putchar(c);
     }
 }