4

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

下面的 C 语言程序来自 text(第 1.5.1 节)通过 putchar() 和 getchar() 将其输入复制到其输出:

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

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

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

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

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

4

4 回答 4

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是接受用户输入的推荐方式)。

于 2013-07-18T08:17:14.903 回答
0

在这里,只要您键入“+”并按 Enter,您输入的所有数据就会被打印出来。您可以将数组的大小增加到 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;


    }

您可以在 '+' 字符或您想表示打印操作的任何字符上设置条件,这样该字符就不会存储在数组中(我现在还没有在 '+' 上设置任何此类条件)

于 2013-07-18T08:10:16.637 回答
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;}
于 2013-07-18T08:28:47.367 回答
-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);
     }
 }
于 2013-07-18T08:17:39.207 回答