【问题标题】:Why I can't concatenate to rebuild and digits arrays the content of c char from text file?为什么我不能从文本文件中连接重建和数字数组 c char 的内容?
【发布时间】:2021-02-07 22:30:17
【问题描述】:

程序失败。我想重建文本文件的内容,例如:a1b2c3 就像 - a1b2c3123,文件末尾的数字

    int counterc=0;
    int counterd=0;
    char rebuild[100];
    char digits[100];
    char c;
    int i;
    FILE *fp;

    fp=fopen("1.txt","r");
    if(fp==NULL)
    {
        printf("\nERROR: File not found for opening\n");
    }
    else
    {
        while(c=fgetc(fp))
        {
            if(c==EOF)
            {
                break;
            }
            if(isdigit(c))
            {
                counterd++;
                strcat(digits,c);
            }
            else
            {
                counterc++;


                strcat(rebuild,c);
            }
        }
    }
    fclose(fp);
    printf("\nNumber of digits: %d ",counterd);
    printf("\nNumber of characters: %d",counterc);

    printf("\nThe content of digits[]: ");

    for( i=0; i<3; i++)
    {
        printf("%s ",digits[i]);
    }
    return 0;
}

如果我不使用strcat(rebuild,c),它将向我打印字符数 如果我不使用strcat(digits,c),它将打印我的位数 为什么我不能将作为数字的字符放在数字数组中?

【问题讨论】:

  • strcat() 用于连接两个字符串,而不是用于添加单个字符。 strcat() 的两个参数都必须是指针。
  • printf("%s ",digits[i]); 也是错误的。 %c 应该用于打印单个字符。

标签: arrays c string file digits


【解决方案1】:

strcat 函数需要两个以 nul 结尾的字符串(char 数组)。 在您的程序中,c 是一个字符,而不是字符数组。

以空字符结尾的字符数组是使用空字符“\0”作为字符串终止符的数组。数组比你在里面存储的要大。

"你好" => 'H' | 'E' | 'L' | 'L' |'O' | '\0' |垃圾|垃圾|等等

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2023-04-06
    相关资源
    最近更新 更多