【问题标题】:Creating and adding string values to a 2D array in C在 C 中创建字符串值并将其添加到二维数组
【发布时间】:2018-08-14 05:44:39
【问题描述】:

您好,我想在 C 中创建一个包含 6 个元素的字符串数组。

示例:

我想保存名字、姓氏、账号、密码、lastTransaction、余额等信息。

我知道如何在 C# 中执行此操作,但无法使用 C 和 char[] 数组来理解它。

我希望输出是 userAccount[0][0] Joe, userAccount[0][1] Bloggs, userAccount[0][2] 123456, userAccount[0][3] 1234, userAccount[0][ 5] 8 月 14 日,userAccount[0][0] 4.25 美元。

【问题讨论】:

  • char *arr[] = {"one", "two", "three", ...};,这是一个指针数组,指向不可修改的chars,或char arr[][256] = {"one", "two", "three", ...}; 用于可修改的数组(256 是数组中每个字符串的最大长度)

标签: c multidimensional-array


【解决方案1】:

先试试这个:

static char* stateNames[] = 
{
  "David Hasselhoff",
  "Lady Gaga" ,
  "Jimmi Hendrix"
};

printf("SER: -> [%s]\n", stateNames[state]);

【讨论】:

  • 将其用作文件中的外部静态变量。在声明它的源文件的其余部分中已知。在文件内的函数中使用 printf。
【解决方案2】:
struct userAccount{
 char name[50];
 char account[50];
 char pin[15];
};

结构最好保存细节

char input[5][256]; 

5= 5 人, 256= 256 列

【讨论】:

    【解决方案3】:

    C 字符串是char 的数组。在您的情况下,数组应该是 3D,第一个索引表示成员数,第二个索引表示成员字段数,第三个索引表示成员信息字段的每个字符串。

    #define MEMBERS 1000 // The maximum number of members you want to store.
    #define FIELDS 6     // (firstName)(lastName)(accountNumber)(password)(lastTransaction)(balance)
    #define LENGTH 12    // The maximum length of field string
    
    char info[MEMBERS][FIELDS][LENGTH] = {
        { "Joe", "Bloggs", "123456", "1234", "14 Aug", "$4.25" },
        ...
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多