CString子串问题

时间:2011-05-30 05:13:45

标签: c++ char substring cstring

我在使用文件i / o实现的子串时遇到问题。我有char数据[21],char world [21]和char eat [21],它们将是[300]中char的子串(这些名称并不代表什么btw)。我想出了一些子字符串代码,而不是获得我想要的子字符串,我得到了整个字符串和一些时髦的字符。有人可以告诉我我做错了什么,或者我过去几个小时是否只是腰部并且库中已经存在子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 个答案:

答案 0 :(得分:2)

char world[21], data[21], eat[21];更改为

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

char world[21]的strlen如果未初始化,则未定义。

答案 1 :(得分:1)

你有几个标准库选项

substr(...) - &gt; http://www.cplusplus.com/reference/string/string/substr/

strstr(...) - &gt; http://www.cplusplus.com/reference/clibrary/cstring/strstr/

:)