在C语言中将字符串存储到数组中

9
据我所知,我可以创建一个带有项目的数组,例如:
char *test1[3]= {"arrtest","ao", "123"};

但是我应该如何将我的输入存储为类似上面代码的数组,因为我只能将其编写为
input[10];
scanf("%s",&input) or gets(input);

它会将每个字符存储到各自的空间中。

如何将输入"HELLO"存储到input[0]中,而不是像现在这样

H 存储到 input[0],E 存储到 input[1],以此类推。


scanf("%s", input)中,input前不需要加上& - Rohan
6个回答

8
你需要一个二维字符数组来创建一个字符串数组:
#include <stdio.h>

int main()
{
    char strings[3][256];
    scanf("%s %s %s", strings[0], strings[1], strings[2]);
    printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}

strings数组中的256是什么意思? - alex
1
@alex 这是每个字符串的长度。因此有一个包含3个字符串的数组,每个字符串有256个字符的空间(实际上只有255个字符,因为字符串末尾总是有一个终止空字符(\0))。 - Zoey Hewll

2
使用二维数组 char input[3][10];

char指针数组(如 char *input[3];),在保存任何值之前应动态分配内存。

第一种情况,将输入值作为 scanf("%s", input[0]);,对于 input[1]input[2] 同样。请记住,您可以在每个 input[i] 中存储最大大小为 10 的字符串(包括 '\0' 字符)。

在第二种情况下,以与上述相同的方式获取输入,但先使用 malloc 为每个指针 input[i] 分配内存。在这里,您可以为每个字符串设置灵活的大小。


0
int main()
{

int n,j;
cin>>n;
char a[100][100];
for(int i=1;i<=n;i++){
    j=1;
    while(a[i][j]!=EOF){
        a[i][j]=getchar();
        j++;
    }
}

2
欢迎来到 Stack Overflow!虽然这段代码可能回答了问题,但提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - ryanyuyu

0

我不是很明白你需要什么。但这是我猜测的。

char *a[5];//array of five pointers

for(i=0;i<5;i++)// iterate the number of pointer times in the array
{
char input[10];// a local array variable
a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here
scanf("%s",input);//take the input from stdin
strcpy(a[i],input);//store the value in one of the pointer in the pointer array
}

当我用printf("%s", input)输出时,如果我输入"HELLO",我的输出应该是"HELLO",而不是"H"。 - MoonScythe

0

尝试下面的代码:

char *input[10];
input[0]=(char*)malloc(25);//mention  the size you need..
scanf("%s",input[0]);
printf("%s",input[0]);

0

这段代码启发了我如何将用户输入字符串放入数组中。我对C语言和本论坛都是新手,如果我没有遵守发布评论的某些规则,请谅解。我正在努力理清思路。

#include <stdio.h>

int main()

{

char strings[3][256];

scanf("%s %s %s", strings[0], strings[1], strings[2]);

printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接