繁体   English   中英

如何在C中将字符串添加到2D数组

[英]How to add a string to a 2D array in C

我开始学习C,并且遇到了将字符串输入添加到2D数组的问题,我能够正确获取字符串输入,但是当我尝试将字符串元素添加到数组时,它无法正常工作当打印数组(这是我测试程序的方式)时,它将为数组中的每个索引分配单个字符,而不是整个字符串。

这是我的查看代码,在此先感谢您,感谢您发布的任何帮助。

#include <stdio.h>
main()
{
    char c_array[3][3];
    int x;
    int y;
    int z=10;
    int i_user_input;
    char c_name[256];


    for(x=0;x<=+2;x++)
    {
        for(y=0;y<=2;y++)
        {
            printf("\nPlease enter a name to the system:");
            scanf(" %s",&c_array[x][y]);
            printf("The string is %s\n",c_name);
            printf("Please press '1' if you would like to keep entering names\n");
            printf("Please press '2' if you would like to print the list of names:");
            scanf("%d",&i_user_input);
            if(i_user_input==1)
                continue;
            if(i_user_input==2)
                for(x=0;x<=2;x++)
                {
                    for(y=0;y<=2;y++)
                    {
                        printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
                    }
                }
        }

    }

}

输出如下,带有示例输入“ Penelope!”。

c_array[0][0]=P
c_array[0][1]=e
c_array[0][2]=n
c_array[1][0]=e
c_array[1][1]=l
c_array[1][2]=o
c_array[2][0]=p
c_array[2][1]=e
c_array[2][2]=!

当您声明时: char c_array [3] [3];

这意味着2D数组的每个元素都是一个“字符”(单个字符)。 不是“字符串”。

要使每个元素都是字符串,您需要以以下方式声明数组:char string_array [3] [3] [256];

我不确定这是您要执行的操作。 Mw的感觉是,您需要3个元素组成的数组,其中每个元素都是一个字符串。 在这种情况下,[3]几乎不够,您的字符串必须少于两个字符(第三个字符保留为终止零)。

如果要为数组中的每个索引分配一个字符串,则按如下所示创建数组:

#include<stdio.h>
int main(void) 
{
    char a[2][10];
    int i=0;
    char temp[20];
    for(i=0;i<2;i++)
    {
        scanf("%s",temp);
        strcpy(a[i],temp);
    }
    printf("%s",a[0]);
    return 0;
}

您输入的每个字符串将存储在数组的每个索引中。

字符串不是类型。 它们是一个值模式,例如,如果您说一个int存储10的倍数,那么它以0结尾...如果您说一个char数组存储一个字符串,那么它以第一个'\\0'结尾,请参见? 我们可以在不同类型的整数变量中存储十的倍数,对于字符串也是如此。

字符串是值的模式,而不是类型。 在选择我们要使用的整数类型时,我们考虑整数的范围。 对于较小的整数值(小于32768),选择int ;对于较大的值(小于2147483648),选择long对于大于该值的值,选择long long 结果,我们根据期望的10的倍数选择正确的整数类型。 同样,对于字符串,我们需要确保我们有足够的存储空间来存储字符串中的字符,并在末尾加上'\\0'

字符&c_array[x][y]仅具有足够的内存来容纳0个字符,后跟一个'\\0' 它仅用于存储空字符串。 也许您打算这样声明c_array

char c_array[3][3][256];

在这种情况下, scanf期望%s对应于char * ...类型的参数,但是由于编译器可能会警告您, &c_array[x][y]的类型将为char (*)[256] 如果要解决该警告,则需要从scanf代码中删除&

if (scanf("%s", c_array[x][y]) != 1) {
    /* XXX: Handle an error here,                *
     * e.g. by exiting or returning or something */
}

当我们讨论该主题时,您会注意到我删除了多余的空间。 %s已经执行了 格式指令将执行。 我还编写了代码来检查scanf的返回值,您应该...


还记得我们谈论过如何选择用于存储数据的整数类型吗? 另一个考虑因素是我们打算存储的数据是否可以是负数 考虑一下:在您的代码中, xy应该能够存储负值? 负数组索引有什么意义? 建议将所有数组索引声明为size_t 当您使用printf打印size_t值时,您将要使用%zu格式说明符而不是%d


char c_name[256];
/* ... */
printf("The string is %s\n",c_name);

现在,如果将字符串存储到c_array[x][y] ,那么c_name的意义是c_name 那是不必要的变量。 使用c_array[x][y]代替。


printf("\nPlease enter a name to the system:");

常见的实现通常会避免打印字符,直到写入'\\n'为止。 该行一次打印,而不是逐个字符打印。 结果,您可能会看到一些奇怪的行为,例如此行未在正确的时间出现。 通过将'\\n'放在行尾而不是开头来解决此问题:

printf("Please enter a name to the system:\n");

...或使用puts ,它会自动为您添加一个'\\ n':

puts("Please enter a name to the system:");

...或使用fflush ,即使没有'\\n' ,它也会写入所有未决的未写入数据:

fflush(stdout);

在你的代码中

scanf(" %s",&c_array[x][y]);
printf("The string is %s\n",c_name);

两种说法都是错误的。

  1. %s需要一个指向数组的指针,而不是单个char 扫描单个char ,您需要%c格式说明符。
  2. printf()使用的c_name未初始化。 使用未初始化的值会调用未定义的行为

解决方案 :要逐个输入元素 ,您可以执行以下操作

for(x=0; x<=2 ;x++)
    {
        printf("Start entering the name, one character at a time\n");
        for(y=0; y< 2; y++)                //note only '<' here
        {
            scanf(" %c", &c_array[x][y]);  // note the leading space
        }
        c_array[x][y] = 0;                 //null termination of array to be used as string
    }
#include <stdio.h>
#include <string.h>

int main(void){
    char c_array[3][3];
    int x;
    int y;
    //int z=10;//unused
    int i_user_input;
    char c_name[256];

    printf("\nPlease enter a name to the system:");
    scanf("%255s",c_name);
    printf("The string is %s\n",c_name);
    printf("Please press '1' if you would like to keep entering names\n");
    printf("Please press '2' if you would like to print the list of names:");
    scanf("%d", &i_user_input);
    if(i_user_input==1)
        ;
    else if(i_user_input==2){
        memcpy(c_array, c_name, sizeof(c_array));
        for(x=0;x<3;x++){
            for(y=0;y<3;y++){
                printf("c_array[%d][%d]=%c\n", x, y, c_array[x][y]);
            }
        }
    }
}

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

#define SIZE 3

int main(void){
    char *c_array[SIZE][SIZE] = { NULL };
    int x;
    int y;
    //int z=10;//unused
    int i_user_input;
    char c_name[256];

    for(x=0;x<SIZE;x++){
        for(y=0;y<SIZE;y++){
            printf("\nPlease enter a name to the system:");
            scanf("%255s", c_name);
            printf("The string is %s\n", c_name);
            printf("Please press '1' if you would like to keep entering names\n");
            printf("Please press '2' if you would like to print the list of names:");
            scanf("%d", &i_user_input);
            c_array[x][y] = strdup(c_name);
            if(i_user_input==1){
                continue;
            }
            if(i_user_input==2){
                int x, y;//local variable
                for(x=0;x<SIZE;x++){
                    for(y=0;y<SIZE;y++){
                        if(c_array[x][y] != NULL)
                            printf("c_array[%d][%d]=%s\n", x, y, c_array[x][y]);
                    }
                }
            }
        }
    }
    for(x=0;x<SIZE;x++)
        for(y=0;y<SIZE;y++)
            free(c_array[x][y]);
}

为什么不在数组/矩阵中使用指针?

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

main()
{
char *c_array[3][3];
int x;
int y;
int z=10;
int i_user_input;
char c_name[256];

for(x=0;x<=+2;x++)
{
    for(y=0;y<=2;y++)
    {
        printf("\nPlease enter a name to the system:");
        scanf(" %s",c_name);
        new_string = malloc(strlen(c_name)+1)
        if (new_string == NULL) {
         print("error allocating string\n")
         exit(-1);
        }
        strcpy(new_string, c_name);
        c_array[x][y] = new_string

        printf("The string is %s\n",c_name);
        printf("Please press '1' if you would like to keep entering names\n");
        printf("Please press '2' if you would like to print the list of names:");
        scanf("%d",&i_user_input);
        if(i_user_input==1)
            continue;
        if(i_user_input==2)
            for(x=0;x<=2;x++)
            {
                for(y=0;y<=2;y++)
                {
                    printf("c_array[%d][%d]=%c\n",x,y,c_array[x][y]);
                }
            }
    }
}
for(x=0;x<=2;x++) {
 for(y=0;y<=2;y++) {
  free(c_array[x][y])
 }
} 
}

如果您的目标是上面的代码,则将输入字符串存储在数组的每个单元格中。

注意:我没有尝试过,因此可能存在细微的错误。 我的观点是向您展示如何使用指针及其与数组的等效性。 没有指针使用C是没有意义的。 :)

暂无
暂无

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

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