2011-05-30 59 views
0

我遇到了與我將用文件I/O實現的子串的問題。我有char數據[21],char world [21]和char eat [21],它們將成爲[300]中char的子串(這些名字不代表任何btw)。我想出了一些子字符串代碼,而不是得到我想要的子字符串,我得到了整個字符串和一些時髦的字符。有人可以告訴我我做錯了什麼,或者如果我剛剛過去幾個小時,圖書館中已經有一個子Cstring方法?CString子串問題

int main() 
{ 
    char in[300] = "w54;d68;n541;" // this is bigger than it needs to be because its for file i/o 
    char world[21], data[21], eat[21]; 
    int w, d, n, end1, end2, end3; 

    for (w = 0; in[w] != 'w'; w++) { 
    } 

    for (end1 = w; in[end1] != ';'; end1++) { 
    } 

    d = end1 + 1; 

    for (end2 = d; in[end2] != ';'; end2++) { 
    } 

    n = end2 + 1; 

    for (end3 = n; in[end3] != ';'; end3++) { 
    } 

    int i; 

    for (i = w + 1; i < end1; i++) { 
     append(world, in[i]); 
    } 

    for (i = d + 1; i < end2; i++) { 
     append(data, in[i]); 
    } 

    for (i = n + 1; i < end3; i++) { 
     append(eat, in[i]); 
    } 

    cout << "world[21]: " << world << endl << "data[21]: " << data << endl << "eat[21]: " << eat << endl; 
} 

void append(char *s, char c) 
{ 
    int len = strlen(s); 
    s[len] = c; 
    s[len + 1] = '\0'; 
} 

,這裏是我的斷點(右前返回0)導致

in 0x0021fbb8 "w54;d68;n541;5468541" char [300] 
end2 7 int 
world 0x0021fb98 "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌw54;d68;n541;5468541" char [21] 
data 0x0021fb78 "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌw54;d68;n541;5468541" char [21] 
eat 0x0021fb58 "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌw54;d68;n541;5468541" char [21] 

n 8 int 
i 12 int 
end3 12 int 
w 0 int 
end1 3 int 
+2

沒有定義[] '作爲字符串,使用'std :: string'類。 – Naveen 2011-05-30 05:21:26

+0

@Naveen:+1,這是這裏真正的答案。然後,OP可以使用'std :: string :: find'而不是編寫手動'for'循環... – Thanatos 2011-05-30 05:31:08

+0

@Naveen我會,但他們不兼容我正在做的文件I/O – 2011-05-30 05:41:37

回答

2

變化char world[21], data[21], eat[21];

char world[21] = {0}; 
char data[21] = {0}; 
char eat[21] = {0}; 

char world[21]的strlen如果如果你正在使用`C++'不要使用普通的`字符不initialized`