c - 如何包含空格?

标签 c arrays file

我正在尝试编写一个程序,从文件中获取单词,并将它们放入动态数组中。然而,当我尝试运行我的代码时,程序会复制除空格之外的所有内容。我该如何解决这个问题?

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 类型的变量。普通 charsigned charunsigned 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/

相关文章:

php - 不考虑 PHP 顺序的字符串比较

java - 无法使用 DateTime 作为名称创建文件夹

c - 在 C 中有效地编辑文件中的单个值

c++ - 在c++中搜索和替换txt文件中的字符串

c - 访问数组元素

ruby - ruby 中的并行分配对于两个等效代码片段的工作方式不同

c - 如何从其成员地址获取结构的起始地址

c - 两个文件在C程序中分别输出一行

c - 使用 strtok 时出现段错误核心转储

c - 向二维数组中的结构成员添加值时出现未处理的异常