【问题标题】:Reading strings of data with delimiter and storing into struct读取带分隔符的数据字符串并存储到结构中
【发布时间】:2014-11-02 08:10:17
【问题描述】:

我需要一些帮助来解决我遇到的一些问题。我是 C 语言的新手,我需要帮助尝试读取带有分隔符的数据字符串并将它们保存到结构中。我该怎么做呢?

字符串的格式如下,格式为 A:B:C:D:E
示例
0002:0001:0001:0042:ASD
0001:0011:0010:0023:DDD

当字符串被读取时,它同时被验证并存储到结构中。

A的值应该在1-100之间
B的值应该在1-100之间
C的值应该在1-10之间
D的值应该在1-50之间
E 的值应在 25 个字符以内。

谁能指导我如何编写代码?如果这听起来很简单,我很抱歉,但我真的很陌生。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   char ch, file_name[25];
   FILE *fp;
   char * aline;
   printf("Enter the name of file you wish to see\n");
   gets(file_name);

   fp = fopen(file_name,"r"); // read mode

   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
     exit(EXIT_FAILURE);
      } 

       printf("The contents of %s file are :\n", file_name);

       while( ( ch = fgetc(fp) ) != EOF ){




   aline=(strtok,":");
   while (aline != NULL)
  {
    printf ("%s\n",aline);
    aline = strtok (NULL, " :");
  }}
     fclose(fp);
   return 0;
}

【问题讨论】:

  • 您可以使用strtok()。您应该发布您的代码,向我们展示您尝试过的内容。您在哪里遇到问题。
  • 我什至不知道如何开始。 ): @1336087
  • 使用fgets 读取一行,strtok 标记您的字符串,strtol 转换每个标记。顺便说一句,这是你的作业吗?
  • @1336087 我不应该/不允许问作业。对不起,我不知道

标签: c pointers struct printf delimiter


【解决方案1】:

您可以使用sscanffscanf 填充结构

sscanf(string, "%d:%d:%d:%d:%26s", &struc->A, &struc->B, &struc->C,
                                   &struc->D,  sturc->E);

fscanf(file, "%d:%d:%d:%d:%26s", &struc->A, &struc->B, &struc->C,
                                 &struc->D,  sturc->E);

要验证字符串,您可以检查空字符是否被覆盖,只需确保使用额外字符声明字符串即可。

if (struc->E[26] != '\0') {
    struc->E[26] = '\0';
    goto invalid;
}

验证其他字段将是简单的边界检查

if (struc->A < 1 || struc->A > 100) goto invalid;

您还应该注意scanf 函数并不总是填充每个字段,并且会返回它们填充的字段数。因此,如果您期望不规则的输入,您应该检查返回的数字。

if (scanf(...) != 5) {
    // either populate with default values or invalidate
}

【讨论】:

  • 我的数据字符串来自文本文件。如何修改 sscanf 以使其工作? @kdhp
  • 我用fscanf添加了一个例子。
  • 谢谢。我如何打印出存储在结构中的数据?我试过printf("%c",&amp;st.E[1]);,但它不起作用。
  • @JamesBond007 在printf 语句中%c 需要一个字符,而您正在向它传递一个指针。 &amp;st.E[1] == &amp;(*(st.E + 1)) == st.E + 1 如果您在字符串的末尾保留一个额外的字符,并使其与'\0' 等价,那么st.E 将以空值结尾,并且可以像任何其他 C 字符串一样处理。 printf("%s", st.E)
  • 我有点困惑。所以你的意思是我应该把我的声明改成printf("%s", st.E)
猜你喜欢
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多