简体   繁体   English

在C中将字符串转换为结构

[英]string to structure conversion in C

Recently i was practicing FILE handling in C, thus i wrote a program which read the file character by character and store the output as string(very long). 最近,我正在C中练习FILE处理,因此我编写了一个程序,该程序逐个字符读取文件,并将输出存储为字符串(很长)。 My file contain various names separated by tab, one line has 3 names as follows. 我的文件包含用制表符分隔的各种名称,一行包含3个名称,如下所示。

Name1 Name2 Name3
Name4 Name5 Name6
Name7 Name8 Name9

As a result of function i wrote, now i have a string[Name1 Name2 Name3 Name4 Name5 Name6 ....] 由于编写了函数,现在我有了一个字符串[Name1 Name2 Name3 Name3 Name4 Name5 Name6 ....]

Now I want to store these names into a structure.. I have written following function for it. 现在,我想将这些名称存储到结构中。.我已经为其编写了以下函数。

  #include<stdio.h>
  #include<stdlib.h>
  #define MAX_LENGTH 30
  struct sarray
  {
  char data[MAX_LENGTH]
  };


  char* stringtoarray(char longstring[],int totalchar,int totaldata)
  {
  int i=0,j=0;
  char che;
  struct sarray say[totaldata];
  char* resultptr;
  che=longstring[i];

  while(che!='NULL')
  {

    if(che=='\t' || che=='\n')
    {
        j++;
        i=0;
    }
    else
    {
        say[j].data[i]=che;
        i++;
    }
    che=longstring[i];
}
resultptr=&say->data;
return resultptr;

}

Following are the arguments to function. 以下是函数的参数。

  1. longstring[] -- It is the string (output of character by character file read) longstring []-它是字符串(按读取的字符文件输出字符)
  2. totalchar -- Total number of characters in the longstring[] totalchar-长串中的字符总数[]
  3. totaldata - Total Number of Names. totaldata-名称总数。

I tried to call the above function from main function, but it is not showing any results, although no error during compilation. 我试图从main函数调用上述函数,但是它没有显示任何结果,尽管在编译过程中没有错误。

Any help would be appreciated. 任何帮助,将不胜感激。

You could do yourself a big favour by reading the format you want in the first place instead of single characters: 您可以通过首先读取所需格式而不是单个字符来帮自己一个忙:

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

#define STR(X)        #X
#define STRINGIFY(X)  STR(X)

#define MAX_TOKEN_LENGTH  30
#define TOKENS_GROWTH      3

typedef struct token_tag {
    char data[MAX_TOKEN_LENGTH + 1];
} token_t;

int main(void)
{
    char const *filename = "test.txt";
    FILE *input = fopen(filename, "r");
    if (!input) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    char token[MAX_TOKEN_LENGTH + 1];
    size_t tokens_size  = 0;
    size_t num_tokens   = 0;
    token_t *tokens     = NULL;

    while (fscanf(input, "%" STRINGIFY(MAX_TOKEN_LENGTH) "s", token) == 1) {
        if (num_tokens == tokens_size) {
            token_t *tmp_tokens = realloc(tokens, (tokens_size + TOKENS_GROWTH) * sizeof(*tmp_tokens));
            if (!tmp_tokens) {
                fputs("Not enough memory :(\n\n", stderr);
                break;
            }
            tokens_size += TOKENS_GROWTH;
            tokens = tmp_tokens;
        }
        memcpy(tokens[num_tokens++].data, token, MAX_TOKEN_LENGTH + 1);
    }
    fclose(input);

    for (size_t i = 0; i < num_tokens; ++i)
        printf("Token #%02zu: \"%s\"\n", i + 1, tokens[i].data);

    free(tokens);
}

Output: 输出:

Token #01: "Name1"
Token #02: "Name2"
Token #03: "Name3"
Token #04: "Name4"
Token #05: "Name5"
Token #06: "Name6"
Token #07: "Name7"
Token #08: "Name8"
Token #09: "Name9"

There are any problems with your code. 您的代码有任何问题。

1/ As already mentioned, you are returning a pointer to locally allocated data. 1 /如前所述,您正在返回一个指向本地分配的数据的指针。 When you declare a local struct/array in a func, space to hold the struct is allocated in the stack and is "lost" when you leave the func. 当在函数中声明本地结构/数组时,用于保存结构的空间会在堆栈中分配,并且在离开函数时会“丢失”。 So the returned pointer will point to garbage. 因此,返回的指针将指向垃圾。

The only way is to allocate the data in the heap with malloc. 唯一的方法是使用malloc在堆中分配数据。

replace struct sarray say[totaldata]; 替换struct sarray say[totaldata]; by 通过

struct sarray *say;
say = (struct sarray *) malloc(totaldata * sizeof(struct sarray));

2/ NULL is not a char. 2 / NULL不是字符。 If you want to test the end of your input string replace while(che != 'NULL') with while(che != '\\0') 如果要测试输入字符串的末尾,请将while(che != 'NULL')替换为while(che != '\\0')

3/ returning &say->data is incorrect. 3 /返回&say->数据不正确。 If you want to get all information, just return a pointer to your array of structs (and change the declaration of the func). 如果要获取所有信息,只需返回一个指向结构数组的指针(并更改func的声明)。

4/ Many sanity checks are missing 4 /许多健全性检查缺失

5/ why do you have an unused parameter in your func (totalchar) 5 /为什么在函子中有未使用的参数(总计)

6/ and you should rethink your algorithm, for instance using scanf as already indicated. 6 /,您应该重新考虑算法,例如,如已指出的那样使用scanf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM