c/c++语言开发共享getchar()并逐行阅读

对于我的一个练习,我们需要逐行阅读并使用ONLY getchar和printf输出。 我正在关注K&R,其中一个例子显示使用getchar和putchar。 从我读到的,getchar()一次读取一个char,直到EOF。 我想要做的是一次读取一个字符,直到行结束,但存储写入char变量的任何内容。 因此,如果输入Hello,World!,它也会将它全部存储在变量中。 我试过使用strstr和strcat但没有成功。

while ((c = getchar()) != EOF) { printf ("%c", c); } return 0; 

    您将需要多个字符来存储一行。 使用例如一系列字符,如下所示:

     #define MAX_LINE 256 char line[MAX_LINE]; int line_length = 0; //loop until getchar() returns eof //check that we don't exceed the line array , - 1 to make room //for the nul terminator while ((c = getchar()) != EOF && line_length < MAX_LINE - 1) { line[line_length] = c; line_length++; //the above 2 lines could be combined more idiomatically as: // line[line_length++] = c; } //terminate the array, so it can be used as a string line[line_length] = 0; printf("%sn",line); return 0; 

    这样,您就无法读取超过固定大小的行(在本例中为255)。 K&R将在以后教您动态分配的内存,您可以使用它来读取任意长行。

      以上就是c/c++开发分享getchar()并逐行阅读相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/559943.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐