繁体   English   中英

如何读取换行符('\\ n')分隔的字符串,直到C中的EOF?

[英]How to read newline character('\n') delimited strings until EOF in C?

例如,我正在编写一个C函数,用新字符串s2替换字符串source的子字符串s1 但是我在读取stdin的输入时遇到了麻烦。 我也希望结束直到达到EOF

我搜索了很多有关“读取直到EOF”和“读取包含空格的字符串”的内容,但是我没有使其正常工作。

#include <stdio.h>
{
  char source[120], s1[20], s2[20];
  ...
  //what ever to input multiple cases of source, s1, and s2 until EOF is met
  replace(source, s1, s2);
  printf("%s\n",source); 

  return 0;
}

您可能想要执行以下操作:

char buffer[1234];

while (NULL != fgets(buffer, 1234, stdin))
{
  /* Do something with the 0-terniated content of buffer. */
}

if (ferror(stdin))
{
   /* An error occurred reading from stdin. */
}

以供参考:


如果不能在换行之前定义字符数的上限,则可能需要关注getline()函数,因为它能够分配必要的内存,以容纳所有字符,直到下一行。

您可以使用feof函数。

while(!feof(stdin)) {
     //read data with scanf, gets, fgets, etc...
}

要发送EOF,请按CTRL+D 查看有关feof函数的更多信息的手册。 man feof上终端)

检查一下,并给我您的意见:

#include <stdio.h>
int Replace_Function(String[] s1,String[]  s2){
String source[120], s1[20], s2[20];

//This is what u want???? 
while (getchar() != EOF)
 {
   S1=S2;
 }

  return 0;
 }

我认为这段代码可以帮助您:

int c;
while ((c = getchar()) != EOF) {
   // do smt
}

我们必须声明c足够大,以容纳getchar返回的任何值。 所以我们从不使用char
c必须足够大以容纳EOF(这是<stdio.h>定义的整数)

暂无
暂无

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

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