【问题标题】:sscanf read till end of the stringsscanf 读取到字符串末尾
【发布时间】:2019-05-14 19:22:44
【问题描述】:

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

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

简而言之,我需要知道格式说明符直到输入字符串的末尾。直到现在我能够让它工作直到看到\n,但不能再使用它了。有人可以帮助阅读直到字符串结束而不是直到看到\n

这里是按比例缩小的例子:

#include <stdio.h>

int main ()
{
  char sentence []="abc@xyz.com 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 abc@xyz.com
evertyhing else is foo bar foobar\nhey there

first column is abc@xyz.com
evertyhing else is foo bar foobar
hey there

【问题讨论】:

  • 我不会为此使用sscanf。麻烦多于值得。
  • @monk 为什么使用 C 进行文本处理?
  • @melpomene 这是套接字程序的一部分,输入是键值,键是一个词,而值是多个词。所以我需要在一个变量中分开键并在另一个变量中作为值。
  • 我正在使用 C 语言的一个模块,这个变化只是其中的一小部分。
  • 你可能会用%n%199c%n做一些可怕的事情。

标签: c scanf


【解决方案1】:

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

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

int main ()
{
  char sentence []="abc@xyz.com 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;
}

【讨论】:

  • 永远不要使用strncpy
  • @melpomene:为什么不呢?如果您知道它的作用,就没有理由不这样做。
  • @melpomene:嗯,这是你的个人观点,没有任何事实支持。在某些情况下,strncpy 正是这项工作所需要的(坦率地说,在此示例中不需要“填充零”行为)。无论哪种情况,这个问题和这个答案都是题外话。
  • 如果 sscanf 有一个返回值检查,我会睡得更好。
  • @monk n%sfirst_str提取的字符串的字符数。所以sentence + n是一个指向句子“其余”开头的指针。
【解决方案2】:
  1. 查找字符串中第一次出现的分隔符。这里的分隔符是单词分隔符,在你的情况下是一个空格。但是很容易将算法扩展为包括制表、换行符、换页符等。
  2. 在那里打印空字节。
  3. 第一列从句子的开头开始,直到写入的空字节。第二列在分隔符之后开始。

下面的代码产生预期的输出:

#include <stdio.h>
#include <string.h>

int main ()
{
    char sentence []="abc@xyz.com foo bar foobar\nhey there";

    char *pnt = strpbrk(sentence, " ");
    if (pnt == NULL) {
        printf("first column is %s\n", sentence);
        printf("there is no second column\n");
        return 0;
    }
    *pnt = '\0';
    pnt++;
    // omit multiple spaces
    while (*pnt != '\0' && *pnt == ' ') pnt++;
    if (*pnt == '\0') {
        printf("first column is %s\n", sentence);
        printf("there is was no second column, tho multiple spaces were found\n");
        return 0;
    }

    char *first_str = sentence;
    char *rest_str = pnt;

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

    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 2018-04-11
    • 2016-08-14
    • 2012-06-06
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多