简体   繁体   English

如何在C中使用空格和多行写法?

[英]How to write using space and more than one line in C?

I want to write a text and save it in .txt using <stdio.h> and <stdlib.h> . 我想编写一个文本,然后使用<stdio.h><stdlib.h>将其保存在.txt中。 But with this way, I only could save one line, no more. 但是用这种方法,我只能保存一行,不能再保存。

int main()
{
   file*pf;
   char kar;

   if ((pf = fopen("try.txt","w")) == NULL)
   {
      printf("File couldn't created!\r\n");
      exit(1);
   }

   while((kar=getchar()) != '\n')
      fputc(kar, pf);

   fclose(pf);
}

Instead of 代替

char kar;

...

while((kar=getchar()) != '\n')
   fputc(kar, pf);

use 采用

int kar;
// Use int for type of kar

...

while((kar=getchar()) != EOF )
                     //  ^^^
   fputc(kar, pf);

'\\n' means end of line. '\\n'表示行尾。 Here, you are looking for end of file. 在这里,您正在寻找文件结尾。 So, use macro EOF instead of '\\n' in your code. 因此,在代码中使用宏EOF而不是'\\n'

Full Working Code which puts multiple line into your text file. 完整的工作代码,可在您的文本文件中添加多行。 To end the input from terminal just press Ctrl + Z 要从终端结束输入,只需按Ctrl + Z

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *pf;
   char kar;

   if ((pf = fopen("try.txt","w")) == NULL)
   {
      printf("File couldn't created!\r\n");
      exit(1);
   }

   while((kar=getchar()) != EOF)
      fputc(kar, pf);

   fclose(pf);

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM