3

我必须用 C 编写一个程序,将换行符作为字符串的一部分处理。我需要一种处理换行符的方法,这样如果遇到它,它不一定会终止输入。到目前为止,我一直在使用fgets(),但是一旦它到达一个'\n'字符就会停止。是否有一个很好的功能来处理来自控制台的不一定以换行符结尾的输入?

澄清:

我需要一种不会在换行符处终止的方法,因为在这个特定的练习中,当遇到换行符时,它会被替换为空格符。

4

4 回答 4

3

fgets从流中获取一行。一行被定义为以换行符、文件结尾或错误结尾,所以你不希望这样。

您可能想使用fgetc. 这是一个ac程序文件的代码示例fgetc.c

#include <stdio.h>

int main (void) {
  int c;
  while ((c = fgetc(stdin)) != EOF) fputc(c, stdout);
}

像这样编译:

cc fgetc.c -o fgetc

像这样使用(注意换行符'\n'):

echo 'Hello, thar!\nOh, hai!' | ./fgetc

或像这样:

cat fgetc.c | ./fgetc

阅读 fgetc 函数手册以了解更多信息:man fgetc

于 2013-08-24T03:24:04.087 回答
2

If I understand your question correctly you want to read from the standard input until user has finished typing ( which ain't be a newline of course ). This can be done by setting a flag like EOF while getting input. One way which I came out with is this:

#include <stdio.h>

int main(void)
{

  char ch;
  char str[100];
  int i = 0;

  setbuf (stdout,NULL);

  while ( (ch = getchar()) != EOF)// user can input until the EOF which he or she enters to mark the end of his/her typing or more appropriately input.
    {
      str[i] = ch;// you can store all the input character by character in a char array 
      i++;
    }
  printf ("%s",str);// then you can print it at last as a whole 
  return 0;
}

BEGINNER's NOTE- EOF can vary from system to system so check it and enter the proper EOF for your system.

于 2013-08-24T04:24:14.410 回答
1

如果您只是阅读信息块而不需要scanf(),那么fread()可能就是您所追求的。但是在控制台上,您可以阅读 \n,注意 \n,如果您认为 \n 不适合您,请继续阅读更多内容。

于 2013-08-24T01:35:35.807 回答
1

scanf按照指示使用时有效。具体来说,它将 \n 视为空白。

根据应用程序的编码方式(即缓冲区的定义方式),a\n会提示系统刷新缓冲区并将数据输入scanf. 这应该作为默认发生,您无需执行任何操作。

所以真正的问题是,你需要控制台提供什么样的数据或字符?在某些情况下scanf,会删除空格,而不是将空格、制表符、换行符传递到您的程序中。但是,scanf可以编码为不这样做!

定义应如何输入数据,我可以指导您如何编写 scanf 代码。

于 2013-08-24T02:21:04.833 回答