This is my first time asking a question on Stackoverflow.
I can’t get a multidimensional vector to output the data when I use array of char and a class.
The below code outputs unexpected characters like “「” and “[B”, although I want it to print “234987 NAME MESSAGE1? 1030.”
Can anybody help me? Thanks.
#include <iostream>
#include <vector>
using namespace std;
class test{
public:
test();
void output();
private:
std::vector< std::vector<char*>> Message_detail;
};
test::test(){
int i = 0;
int j = 0;
char input[] ="USERID=234987+USERNAME=NAME+MESSAGE=MESSAGE1?+TIME=1030&USERID=12304234+USERNAME=NAME2UKI+MESSAGE=HIII+TIME=1330&USERID=1376321+USERNAME=JONES12+MESSAGE=GENKI DAYO+TIME=1025";
char * pch;
pch = strtok (input,"+=&");
Message_detail.push_back( vector<char*>() );
while (pch != NULL)
{
if((int)Message_detail[j].size() == 4){
Message_detail.push_back( vector<char*>() );
j++;
}
if(strlen(pch) < 1){
Message_detail.pop_back();
}
if(i % 2 != 0){
Message_detail[j].push_back(pch);
}
i++;
pch = strtok (NULL, "+=&");
}
}
void test::output(){
for(vector<char*>::size_type i = 0; i < Message_detail.size(); i++){
for(vector<char*>::size_type j = 0; j < Message_detail[i].size(); j++){
std::cout << Message_detail[i][j] << endl;
}
}
}
void main(){
test hello;
hello.output();
}
char input[]is a local variable, what this means is that it expires at the}at the end of the constructor. All the pointers in the vector are pointing at locations to this local variable. If you change the code tostatic char input[]or use a global array, etc. the code should work correctly because you have now made sure that the array exists for the lifetime of the program.Other notes:
void main()toint main()to be a C++ conforming program.#include <cstring>forstrtok, etc.