2010-02-27 77 views
5

我的問題是在字符串轉換爲字符串 我必須傳遞給strcat()一個字符附加到字符串,我該怎麼辦? 謝謝!C字符串(通過字符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; 
} 

回答

5

由於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; 
} 
3

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風格字符串的結束。確保你的輸出字符串在最後用零終止符初始化,否則這個例子將失敗。

另外:想想*in++;是做什麼的。它將增加in並對其進行解引用,這與in++非常相似,因此*是無用的。

1

看你的代碼,我可以做一些關於它的指針,這不是批評,藉此與少許鹽,將使你成爲一個更好的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; 
} 

希望這有助於 最好的問候, 湯姆。

+0

使用「ASD」功能允許ASD在其它環境中使用,允許main忽略asd本身的計算。 我總是會選擇一個功能,無論情況如何。 – 2010-02-27 13:56:00

+0

此外,你的memset()是完全不相關的,只需聲明如下: char ok [200] = {0}; – 2010-02-27 13:56:28

+0

@rogue:如果你願意,你可以這樣做,沒有明確的方式,無論是你的方式或我提到的方式,注意到評論標記OR和memset ......無論哪種方式取決於你的風格! – t0mm13b 2010-02-27 14:05:10

0

一個字符轉換成你可以簡單地做一個(空結尾的)字符串:

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

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

+0

由於'c'仍然是'char'類型,所以不起作用。 'sprintf'希望能夠使用字符串。 – skytreader 2014-02-11 05:50:36

+0

這實際上似乎工作。如果sprintf在格式字符串中填充'%c',它可以接受一個字符參數。 – 2015-12-23 16:01:47