【问题标题】:How to separate a string delimitated by @ in a txt file on a c program?如何在c程序的txt文件中分隔由@分隔的字符串?
【发布时间】:2014-10-15 16:48:48
【问题描述】:

我有一个 txt 文件,我必须在 c 程序中读取,该文件包含一串以@分隔的数字,它看起来像这样:

-24.5@5.23@4.58@112.1275@524963.8974632841@18.37343308266859@1412046264002

我使用fopen函数将文件上传到程序,并用fprintf打印出来,但我还没有找到分离数字的方法

我找到了这个方法,但它不起作用:

sscanf(line, "%s\t%s", position, activity);

有什么建议吗?

【问题讨论】:

  • “它不起作用”是什么意思?解释您观察到的行为是绝对必要的。

标签: c delimiter


【解决方案1】:

您可以使用strtok 函数。举个例子:

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

int main()
{
   const char str[100] = "-24.5@5.23@4.58@112.1275@524963.8974632841@18.37343308266859@1412046264002";
   const char s[2] = "@";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while (token != NULL) 
   {
      printf("%s\n", token);
      token = strtok(NULL, s);
   }

   return(0);
}

【讨论】:

  • const char str[100] --> char str[100]
  • +1 非常感谢,这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2012-04-14
  • 2016-07-15
  • 1970-01-01
  • 2011-08-04
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多