如何解决CString子字符串问题
| 我在使用文件I / O实现的子字符串时遇到麻烦。我有char数据[21],char world [21]和char eat [21],它们将是char in [300]的子字符串(名称不表示任何东西)。我想出了一些子字符串代码,而不是得到我想要的子字符串,而是得到了整个字符串和一些时髦的字符。有人可以告诉我我做错了什么吗,或者如果我过去几个小时都束手无策,并且库中已经有一个sub-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
解决方法
将
char world[21],data[21],eat[21];
更改为
char world[21] = {0};
char data[21] = {0};
char eat[21] = {0};
如果未初始化char world[21]
的strlen,
, 好吧,您有几个标准库选项
substr(...)-> http://www.cplusplus.com/reference/string/string/substr/
要么
strstr(...)-> http://www.cplusplus.com/reference/clibrary/cstring/strstr/
:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。