【问题标题】:How do I use scanf (not fgets) to read in lines of text?如何使用 scanf(而不是 fgets)读取文本行?
【发布时间】:2017-09-18 17:38:50
【问题描述】:

我需要编写一个程序,从输入中读取(可能)多行文本。该程序需要使用 scanf 和 printf,并且没有其他库函数(所以没有 fgets、getchar 或其他任何东西。

我知道可以在一行中使用以下内容:

  scanf("%[^\n]s", text);

但这留下了一个 \n ,其中:

a) 需要添加到名为 text 的数组的末尾

b) 阻止其余的输入行被读入。

这是我到目前为止的代码

void print_line()
{
  int i = 0;

  while(i < 12)
  {
      char input_text[100];


      /*printf("Input text here: ");*/
      /*scanf("%[^\n]s\n", input_text);*/
     /*EDIT */
      scanf("%99[^\n]", input_text);

      /*Can't use fgets*/
     /*fgets(input_text, 100, input);*/
     printf("Text: %s", input_text);

     i++;
  }  

}

我已经运行了它,它只读取文件的第一行并重复 12 次。

编辑: 有人建议我试试这个:

      scanf(" %99[^\n]", input_text);

哪种方法有效,它读入了所有输入行,但它作为一个大行将它们全部读入,忽略了换行符和缩进字符(空格、制表符等)。

【问题讨论】:

  • 如果是我,知道我今天所知道的,我会故意不及格这个作业。尝试使用scanf 读取输入行没有任何好处——nothing!。它纯粹是徒劳的。完成这个练习后,你最多会学到一些你永远不需要知道的东西,最坏的情况是你可能会被诱导使用你新发现的知识来编写尝试使用scanf读取输入的生产程序,这对你有用(和那些程序)一点都不好。
  • 说真的:告诉你的导师这是一个糟糕的任务。
  • "我知道可以在一行中使用以下内容:scanf("%[^\n]s", text);" --> 行很短或很长时都不好用。
  • @SteveSummit 同意两个 cmets,除了我遇到了 scanf()fgets() 的 1 个角落使用。 if (scanf("%99[^\n]%n", input_text, &amp;n) == 1) { ... 允许代码检测是否读取 空字符,因为 n 是真实长度。 fgetc()getline() 当然是其他选择。
  • SilentDrew 在 C 中,一行 文本包括 '\n'。 “每一行由零个或多个字符加上一个终止换行符组成。” C11 7.21.2 2. 在帖子中指定input_text[100]; 是否应该在函数结束时包含'\n'

标签: c scanf


【解决方案1】:

请阅读scanf 的手册页。删除格式字符串中的s。检查返回值为weĺl。

【讨论】:

  • 还要在 % 后面加上 99 来停止溢出
【解决方案2】:

这将尝试读取一行到换行符,然后读取换行符。如果result 为零,则流中有换行符,if 将尝试读取换行符。

    char input_text[100];
    char newlines[100];
    int result = 0;

    do {
        result = scanf("%99[^\n]%99[\n]", input_text, newlines);//scan line to newline then trailing newline
        if ( result == 0) {
            result = scanf("%99[\n]", newlines);//scan leading newline
        }
        if ( result == 1) {
            printf("Text: %s\n", input_text);//no newline so print line with newline
        }
        if ( result == 2) {
            printf("Text: %s%s", input_text, newlines);//print line and newlines
        }
    } while ( result != EOF);

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多