c - sscanf 读取直到字符串末尾

标签 c scanf

我需要将字符串分成两部分,字符串的第一列是第一部分,字符串的其余部分是第二部分。第一部分需要存储在 first_str 中,第二部分需要存储在 rest_str 中。

我正在使用 sscanf 来实现结果,当 sentence[] 不包含任何文字 时,我设法通过以下示例获得所需的输出\n

简而言之,我需要知道格式说明符直到输入字符串的末尾。到目前为止,我能够使其工作直到看到 \n ,但无法再使用它。有人可以帮助阅读直到字符串末尾而不是直到看到 \n 吗?

这是缩小的示例:

#include <stdio.h>

int main ()
{
  char sentence []="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25444746655d5c5f0b464a48" rel="noreferrer noopener nofollow">[email protected]</a> foo bar foobar\nhey there";
  char first_str [200];
  char rest_str [200];

  //sscanf (sentence,"%s %99[^\0]",first_str,rest_str);
  sscanf (sentence,"%s %99[^\n]",first_str,rest_str);

  printf ("first column is %s\nevertyhing else is %s\n",first_str,rest_str);

  return 0;
}

期望的结果:

first column is <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7d7e7f5c646566327f7371" rel="noreferrer noopener nofollow">[email protected]</a>
evertyhing else is foo bar foobar\nhey there

或者

first column is <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d6c6f6e4d757477236e6260" rel="noreferrer noopener nofollow">[email protected]</a>
evertyhing else is foo bar foobar
hey there

最佳答案

sscanf 支持 %n 格式说明符来返回消耗的字符数。您可以使用它来确定 sscanf 消耗了前缀的长度。

以下代码将 rest_str 设置为指向“字符串的其余部分”:

int main ()
{
  char sentence []="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0818283a098999ace838f8d" rel="noreferrer noopener nofollow">[email protected]</a> foo bar foobar\nhey there";
  char first_str [200];
  char *rest_str;

  int n = 0;
  sscanf (sentence,"%s %n",first_str,&n);
  rest_str = sentence + n;

  printf ("first column is %s\nevertyhing else is %s\n",first_str,rest_str);

  return 0;
}

关于c - sscanf 读取直到字符串末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56137266/

相关文章:

执行 "sudo -s"命令时,c 程序挂起/循环

c - 从 Matlab C mex 函数返回 C 结构中的大型数组的最有效内存方法是什么?

c - 调试词法分析器问题

c - 为什么在 %*c 周围使用空格

c - 当我在 Xcode 中使用命令行工具输入内容时,代码会在我第一次输入时忽略它。为什么会这样,有没有办法避免呢?

c - 如何在LPC 1768(C编程)中使用定时器每1秒闪烁一次LED?

C: 类型结构的不完整定义

c - 使用 fscanf 从文件中读取字符串后读取整数

c - scanf 之后 fgets 不起作用

c - 读取单词直到行尾