我正在尝试创建一个长度为80的未知数量的字符串。
int main(int argc, const char * argv[]) {
char str[81];
readIn(str);
return 0;
}
void readIn(char arr[])
{
int k=0;
while ((arr[k] = getchar()) != '\n')
{
k++;
}
}
我希望我的readIn函数循环并将每个循环存储为新字符串,直到用户输入空字符串。我在考虑二维数组(一个用于字符串长度,一个用于字符串数量),但即使这样,也需要固定数量的两个维度。
我愿意接受任何解决方案。 感谢
答案 0 :(得分:0)
您可以根据需要使用动态分配来增加数组的大小。这样做:
#include <stdlib.h>
#include <stdio.h>
// (!) readIn is not safe (the user may input more than 79 characters per line)
// also, the program may crash if the user types an end-of-input (ctrl-D)
void readIn(char *arr) {
int k;
for (k = 0; (arr[k] = getchar()) != '\n'; ++k) ;
arr[k] = '\0'; // end-of-string character
}
...
int alloc = 2; // capacity of the array of strings
int length; // current position in the array of strings (and finally length)
char **strArray = calloc(alloc, sizeof(char *)); // array of strings
for (length = 0; ; ++length) {
if (length >= alloc) { // increase the size if necessary
alloc *= 2; // doubles the allocated space
strArray = realloc(strArray, alloc * sizeof(char *));
}
strArray[length] = calloc(80, sizeof(char)); // allocates string of length 80
readIn(strArray[length]);
if (strArray[length][0] == '\0') // if the first character is end-of-string, the string is empty
break; // go out from the cycle
}
// now "length" contains the length of strArray
...
答案 1 :(得分:-1)
C中的动态大小的数组很难。但是要创建一个字符串数组,这很简单:
char arrayOfStrings[Number of Strings][Length of Each String];
char arrayOfStrings[100][80];
strcpy(arrayOfStrings[0], "String Number One");
strcpy(arrayOfStrings[1], "String Number Two");
void readIn(char arrayOfStrings[][])
{
int i = 0;
int ii = 0;
while (arrayOfStrings[ii][0] != '\n' && ii <= 100) // Just an 'Enter'
i = 0;
while ((arrayOfStrings[ii][i] = getchar()) != '\n' && i <= 80)
{
i++;
}
ii++;
}
}