【问题标题】:Random spaces added when using strcat使用 strcat 时添加的随机空格
【发布时间】:2017-07-12 17:42:51
【问题描述】:

我正在尝试不断地将 char 添加到字符串的末尾。我通过在我的 main 中运行它来做到这一点

 char String[256];
char alphabets[26] = "abcdefghijklmnopqrstuvxyz";
for (int i = 0; i < 257; i++) {

            char newChar = alphabets[indexOfNewChar-1];
            printf("new char = %c\n",newChar);
            strcat(String,&newChar);

            printf("%s\n",String);
}

当我运行这堆代码时,这是打印出来的 new char = b bkhobtj dfhhai bbdhgfcafgcfi bbaccfeai afebaci aedgdddai hei hfedhbi dabeedbi i cfhi i caddbhgbi i acfi cehbhcddcahbhbabi aaadi hi ffhhccbccfbbfggfdhebgeacecai cefdcdb

如您所见,在运行过程中会随机出现空格和换行符。 在意识到这些随机空格的出现后,我尝试用

删除空格
char* removeSpaces(char* input)
{
    int i,j;
    char *output=input;
    for (i = 0, j = 0; i<strlen(input); i++,j++)
    {
        if (input[i]!=' ')
            output[j]=input[i];
        else
            j--;
    }
    output[j]=0;
    return output;
}

但是,这并没有真正影响结果,因为仍然出现空白。如何删除这些空格或更好地阻止它们出现。 在旁注中,代码在 for 循环重复 160 多次后终止。我该如何克服这个问题。

【问题讨论】:

  • 1) char String[256]; --> char String[256] = "";char String[256]; *String = 0;
  • 2) i &lt; 257; --> i &lt; sizeof(String)-1;
  • 3) strcat(String,&amp;newChar); --> strncat(String, &amp;newChar, 1);
  • 旁白:建议char alphabets[27] = "abcdefghijklmnopqrstuvxyz";char alphabets[] = "abcdefghijklmnopqrstuvxyz"; 以便可以包含字符串终止符。
  • @Chandrasekaran Dinesh 变量indexOfNewCha的定义在哪里?提供最小编译函数。

标签: c xcode strcat


【解决方案1】:

newChar 是单个char&amp;newChar 不是一个字符串。一个字符串需要一个空终止符; strcat 正在寻找一个,并将找到的杂散字符连接起来,直到找到一个(尽管这是未定义的行为,因此可能导致程序崩溃)。

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多