我正在尝试编写一个程序,从文件中获取单词,并将它们放入动态数组中。然而,当我尝试运行我的代码时,程序会复制除空格之外的所有内容。我该如何解决这个问题?
This is a test does it work?
但我得到以下信息:
Thisisatestdoesitwork?
char** getWords(char* filename, int* pn){
char** tmp = (char**)malloc( 1000*sizeof(char));
int *temp=(int*)malloc(1000*sizeof(int);
int c;
int counter = 0;
FILE* fileInput = fopen(filename, "r");
if(fileInput == NULL){
return tmp; // return if file open fails
}
while((c=fgetc(fileInput)) != EOF){
result = fscanf(fileInput, "%c", &c); //try to read a character
if(isalpha(c)){ //chararect alphabetical
tmp[counter] = c; // safe int to array
counter ++;
printf("%c", c); fflush(stdout);
}
else{ // if read not succesfull
fscanf(fileInput, ""); // needs to scan anything not a character
}
if(counter > 100){ // to not exceed the array
break;
}
if(feof(fileInput)){ // to check if at the end of the file
break;
}
}
fclose(fileInput); // closing file
*pn = counter;
return tmp;}
我的主要功能:
int main(int argc, char* argv[]){
int n;
char** a = getWords("opdracht_4_5.c", &n);
if (a != NULL){
puts("gevonden woorden:");
for (int i = 0;i < n; i++){
printf("%3d %s\n",i,a[i]);
}
for (int i = 0;i < n; i++){
free(a);
}
free(a);
}
return (EXIT_SUCCESS);
}
最佳答案
您的代码存在不少问题。这是一个开始:
- 您不测试
fopen()
的返回值。 - 您不测试
malloc()
的返回值。 - 将
fgetc()
的返回值分配给char
类型的变量。普通char
与signed char
或unsigned char
兼容。为了区分字符和EOF
(负数),fgetc()
函数返回转换为unsigned char< 的字符
(或 EOF)。您需要测试EOF
然后将值转换为纯char
。 is...()
函数需要一个int
参数,其值在unsigned char
范围内 或EOF
。如果您有一个普通的char
,您首先必须将其转换为unsigned char
,或者您可以直接传递fgetc()
的返回值到isalpha()
。- 您尝试将零长度
char
数组 (temp
) 附加到未初始化的char
数组 (s
>),并且您不测试目标数组中是否有足够的空间。这个问题被破坏的原因比我想列举的还要多。 - 您为包含 1000 个指向
char
的指针的数组分配内存,但从未为char
指针本身分配内存。 - 您尝试将缓冲区 (
s
) 附加到未初始化的指针 (*tmp
)。 - 您对非 null 终止的内容调用
strlen()
。 - 您永远不会返回数组的长度。
- 您调用了许多尚未声明的函数。
关于c - 如何包含空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24476132/