2

Stackoverflow で質問するのはこれが初めてです。

char の配列とクラスを使用すると、データを出力するための多次元ベクトルを取得できません。

以下のコードは、「234987 NAME MESSAGE1? 1030」を出力したいのですが、「「」や「[B」などの予期しない文字を出力します。

誰でも私を助けることができますか?ありがとう。

#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();
}
4

2 に答える 2

1

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 to static 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:

  • Change void main() to int main() to be a C++ conforming program.
  • I don't see a #include <cstring> for strtok, etc.
于 2012-08-22T00:41:13.367 に答える
0

次の出力:

名前 メッセージ1? 1030 12304234 NAME2UKI HIII 1330 1376321 JONES12 げんきだよう 1025

次のプログラムで生成しています。

#include <cstdio>
#include <cstring>

int main ()
{
    char * pch;
    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";
    pch = strtok (input,"U");
    while (pch != NULL)
    {
        pch = strtok (NULL, "=");      
        if ( pch == NULL ) break;
        pch = strtok (NULL, "+&");      
        printf ("%s\n",pch);
    }
    getchar();
    return 0;
}

ただし、多次元ベクトルは使用しません。

于 2012-08-22T01:24:52.783 に答える