开发者

CString Substring problem

I am having trouble with substrings that I will implement with file i/o. I have char data[21],char world[21], and char eat[21] that will be substrings of char in[300] (the names dont mean anything btw). I came up with some substring code and instead of getting the substring I wanted, I get the whole string and some funky characters. Can someone tell me what I'm doing wrong, or if I just waisted the past couple hours and there already is a sub-Cstring method in the library?

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 < end开发者_StackOverflow社区2; 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';
}

and here are my breakpoint (right before return 0) results

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


Change char world[21], data[21], eat[21]; to

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

strlen of char world[21] is not defined if its not initialized`


Well you have a couple of standard library options

substr(...) -> http://www.cplusplus.com/reference/string/string/substr/

or

strstr(...) -> http://www.cplusplus.com/reference/clibrary/cstring/strstr/

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜