C-如何在数组中存储多个字符串 [英] C - how to store multiple strings in an array
问题描述
想知道如何在数组中存储不同的字符串. 例如,用户输入"qwe",然后程序会将其存储在数组变量[0]中.输入另一个字符串,然后将其存储为变量[1],依此类推
Wondering how store different strings in an array. For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on
int
main(int argc, char *argv[]) {
char variable[1000];
int i;
printf("enter a variable\n");
scanf("%s", variable);
for (i = 0; ??? ;i++) {
printf("The variable entered was: %s\n",variable[i]);
}
return 0;
我是C语言的新手,所以我不知道我在做什么.但这就是到目前为止我想出的,我想知道我是否可以得到一些帮助来填补其余的内容 谢谢!
Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest Thanks!
推荐答案
您可以使用2D数组存储多个字符串.对于10个长度为100的字符串
You can use 2D array to store multiple strings. For 10 strings each of length 100
char variable[10][100];
printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)
scanf("%100s", variable[i]);
更好地使用fgets
读取字符串.
Better to use fgets
to read string.
fgets(variable[i], sizeof(variable[i]), stdin);
您还可以通过使用指向char
的指针数组来使用动态内存分配.
You can also use dynamic memory allocation by using an array of pointers to char
.
这篇关于C-如何在数组中存储多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!