如何将字符串添加到 C 中的二维数组 [英] How to add a string to a 2D array in C
问题描述
我开始学习 C 并且遇到了将字符串输入添加到二维数组的问题,我能够正确获取字符串输入但是当我尝试将字符串元素添加到数组时它不是按预期工作.打印数组时(这是我测试程序的方式),它将为数组中的每个索引分配一个字符,而不是整个字符串.
i am starting to learn C and I have ran into the problem of adding a string input to a 2D array, i am able to get the string input correctly but when i try and add the string element to the array it is not working as expected.When printing the array(which is how i test the program) it will assign each index in the array a single character instead of the entire string.
这是我供查看的代码,非常感谢您,感谢您发布的任何帮助.
And here is my code for viewing, thank you very much in advance i appreciate any help that is posted.
#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("
Please enter a name to the system:");
scanf(" %s",&c_array[x][y]);
printf("The string is %s
",c_name);
printf("Please press '1' if you would like to keep entering names
");
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
",x,y,c_array[x][y]);
}
}
}
}
}
输出如下所示,输入示例为Penelope!"
The output looks as follows with the sample input '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];
这意味着二维数组的每个元素都是一个字符"(单个字符);不是字符串".
This means that each element of your 2D array is a "char" (a single character); not a "string of characters".
为了让每个元素都是一个字符串,你需要用以下方式声明你的数组:char string_array[3][3][256];
To have each element be a string of characters, you need to declare your array in the following way: char string_array[3][3][256];
我不确定这是否是您想要做的.Mw 感觉是您想要一个包含 3 个元素的数组,其中每个元素都是一个字符串.在这种情况下,[3] 还不够,您的字符串必须少于两个字符(第三个字符保留用于终止零).
I am not sure this is what you want to do though. Mw feeling is that you want an array of 3 elements where each element is a string. In that case, [3] is hardly enough, your strings will have to be less than two characters (the third being reserved for the terminating zero).
这篇关于如何将字符串添加到 C 中的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!