我需要将字符串分成两部分,字符串的第一列是第一部分,字符串的其余部分是第二部分。第一部分需要存储在 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/