【问题标题】:C - create members of struct in loop?C - 在循环中创建结构的成员?
【发布时间】:2015-08-25 11:33:58
【问题描述】:

我是 C 编程的新手,想编写一个程序来读取一行整数,然后为每个整数创建一个结构的成员。这是一个简化的例子:

假设这是一行:*23 4 12 56 78 *

结构看起来像这样:

struct structure
{
    int index;
    int number;
};

第一个成员应该是这样的:

struct structure member0;

member0.index = 0;
member0.number = 23;

但是我希望程序能够读取任意长度的行,所以我想要一个循环,每当读取一个整数时,它会使用读取的数字和一个将名称和索引设置为 previous index + 1,我想知道是否以及如何做到这一点。

【问题讨论】:

  • 这样做当然可以,你试过什么?
  • 展示你的尝试
  • 使用数组还是链表?
  • 为此使用数组。
  • 我建议使用strtok 来阅读数字。

标签: c loops struct initialization


【解决方案1】:

可以的

  1. 使用fgets() 读取该行
  2. 使用strtok() 将行分成令牌
  3. 使用atoi()strtol() 将每个标记转换为整数
  4. 保留一些变量,比如 i,您需要为每个令牌递增,并且应该在每次 fgets() 调用后重置
  5. 拥有结构的动态或静态数组来保存上述信息

【讨论】:

    【解决方案2】:

    使用strtol(),你会想要一些类似的东西..

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    
    #define MAX_SIZE 100
    
    typedef struct _TMember
    {
        int index;
        int number;
    } TMember;
    
    int main()
    {
        TMember arr[MAX_SIZE] = {};
    
        char szNumbers[] = "10 20 30 40 50";
        char *pEnd;
    
        long int li;
        unsigned short index = 0;
        pEnd = szNumbers;
        for( ; ; )
        {
            char *tmp = pEnd;
    
            li = strtol( pEnd, &pEnd, 10 );
            if( tmp == pEnd )
            {
                break;
            }
            else
            {
                arr[index].index = index;
                arr[index].number = li;
                index++;
            }
        }
    
        for( int i = 0; i < index; i++ )
        {
            printf( "Member %d, idx = %d, number = %d\n", i, arr[i].index, arr[i].number );
        }
    
        return 0;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 2017-02-09
      • 1970-01-01
      • 2020-08-15
      • 2021-12-27
      • 1970-01-01
      • 2013-11-05
      • 2011-04-18
      • 2018-05-06
      相关资源
      最近更新 更多