c - 如何在C中一一获取字符串的输入

标签 c regex fgets

我必须接受如下输入,并打印相同的内容(仅句子):

2

I can't believe this is a sentence.

aarghhh... i don't see this getting printed.

数字 2 显示要遵循的行数(此处在此之后 2 行)。 我使用了所有选项 scanf 和 fgets 以及各种正则表达式。

int main() {
  int t;
  char str[200];
  scanf ("%d", &t);      
  while (t > 0){
  /* 
  Tried below three, but not getting appropriate outputs
  The output from the printf(), should have been:

  I can't believe this is a sentence.
  aarghhh... i don't see this getting printed.
  */
    scanf ("%[^\n]", str);
    //scanf("%200[0-9a-zA-Z ]s", str);
    //fgets(str, 200, stdin);
    printf ("%s\n", str);
    t--;
  }
}

抱歉,我已经搜索了所有相关帖子,但找不到任何答案: 所有版本的 scanf() 都不会产生结果,而 fgets() 只打印第一句话。 提前致谢。

最佳答案

您应该只使用fgets()。请记住,它将保留换行符,因此您可能需要在阅读该行后手动删除换行符:

if(scanf("%d", &t) == 1)
{
  while(t > 0)
  {
    if(fgets(str, sizeof str, stdin) != NULL)
    {
      const size_t len = strlen(str);
      str[len - 1] = '\0';
      printf("You said '%s'\n", str);
      --t;
    }
    else
      printf("Read failed, weird.\n");
  }
}

关于c - 如何在C中一一获取字符串的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22501040/

相关文章:

c - 尝试用 C 从头开始​​构建 BST 树

PHP 正则表达式 : Get domain from URL

java - 使用 Java + 正则表达式从文本文档中提取 URL

regex - 正则表达式匹配后未定义 Perl $1 变量

c - 为什么程序会因使用 '%s' 取消引用 char 指针而崩溃?

c - printf 是否需要 %zu 说明符?

c - time_t 的转换如何在 C 中工作?

c - 奇怪的 strncpy、fgets 行为

C fgets 读取行

c - "Segmentation Fault (core dumped)"是什么?为什么它会在我的输出中返回?