为什么用vector<char*>不能输出正确的值?
因为数组是事先开辟好的,pushback进去的是数组的地址,所以无论你怎么改输入的内容,都是把一个相同的东西存进去。
解决方法 重新定义一个char *temp_buf = new char[10] 然后strcpy,再push_back进去。
C++代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
#include<string>
#include<vector>
using namespace std;
int main() {
char buf[1024] = "10 5 12 43 76 89 97";
int len = strlen(buf);
vector<char*> str_v;
char temp_buf[10];
memset(temp_buf, '\0', sizeof(temp_buf));
int k = 0;
for (int i = 0; i < len; i++) {
if (buf[i] >= '0' && buf[i] <= '9')
{
temp_buf[k] = buf[i];
k++;
}
if (buf[i] == ' ') {
char *real_buf = new char[10];
strcpy(real_buf, temp_buf);
str_v.push_back(real_buf);
memset(temp_buf, '\0', sizeof(temp_buf));
k = 0;
}
}
for (int i = 0; i < str_v.size(); ++i) {
cout << str_v[i] << endl;
}
return 0;
}
运行结果: