簡體   English   中英

C char to string(將char傳遞給strcat())

[英]C char to string (passing char to strcat())

我的問題是將char轉換為字符串我必須傳遞給strcat()一個字符串附加到字符串,我該怎么辦? 謝謝!

#include <stdio.h>
#include <string.h>

char *asd(char* in, char *out){
    while(*in){
        strcat(out, *in); // <-- err arg 2 makes pointer from integer without a cast
        *in++;
    }
    return out;
}

int main(){
    char st[] = "text";
    char ok[200];
    asd(st, ok);
    printf("%s", ok);
    return 0;
}

由於ok指向未初始化的字符數組,因此它們都是垃圾值,因此串聯(通過strcat )將在何處開始是未知的。 strcat采用C字符串(即由'\\ 0'字符終止的字符數組)。 char a[200] = ""會給你一個[0] ='\\ 0',然后[1]到[199]設置為0。

編輯:(添加了更正的代碼版本)

#include <stdio.h>
#include <string.h>

char *asd(char* in, char *out)
{

/*
    It is incorrect to pass `*in` since it'll give only the character pointed to 
    by `in`; passing `in` will give the starting address of the array to strcat
 */

    strcat(out, in);
    return out;
}

int main(){
    char st[] = "text";
    char ok[200] = "somevalue"; /* 's', 'o', 'm', 'e', 'v', 'a', 'l', 'u', 'e', '\0' */
    asd(st, ok);
    printf("%s", ok);
    return 0;
}

strcat不會附加單個字符。 相反,它需要一個const char* (一個完整的C風格的字符串),它附加在第一個參數的字符串中。 所以你的函數應該是這樣的:

char *asd(char* in, char *out)
{
    char *end = out + strlen(out);

    do
    {
        *end++ = *in;

    } while(*in++);

    return out;
}

do-while循環將包括在C樣式字符串結尾處必需的零終止符。 確保您的out字符串在結尾處使用零終止符進行初始化,否則此示例將失敗。

除此之外:想想*in++; 確實。 這將增加in和取消對它的引用,這是非常相同in++ ,所以*是沒用的。

為了查看你的代碼,我可以提出一些與之相關的指示,這不是一個批評,用一點鹽來實現,這將使你成為一個更好的C程序員:

  • 沒有功能原型。
  • 指針使用不正確
  • 處理strcat函數使用不正確。
  • 過度使用 - 不需要asd功能本身!
  • 處理變量的用法,特別是未正確初始化的char數組。
#include <stdio.h>
#include <string.h>

int main(){
    char st[] = "text";
    char ok[200];
    ok[0] = '\0'; /* OR
    memset(ok, 0, sizeof(ok));
    */
    strcat(ok, st);
    printf("%s", ok);
    return 0;
}

希望這會有所幫助,最好的問候,湯姆。

要將字符轉換為(空終止)字符串,您可以簡單地執行以下操作:

char* ctos(char c)
{
    char s[2];
    sprintf(s, "%c\0", c);
    return s;
}

工作示例: http//ideone.com/Cfav3e

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM