簡體   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