• 締切済み

vectorを使っていたいのですが上手くいきません

文字列(A)から特定の文字列(B)を抽出しながらvectorにどんどん入れていくプログラムを作成しています。(文字列(B)の位置や長さはわかっているとします。) そこで、文字列(A)から、文字列(B)に相当するアドレスをvectorにどんどん入れているのですが、先pushした値が後からpushした値と全て同じ値になってしまいます。 これは、アドレス渡しが原因と分かってはいるのですが、どう書けば上手くいくかわかりません。 そこでご教授頂きたいと思っています。 自分が書いたプログラムは以下になります。 #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> using namespace std; void main(){ char* stringA; vector<char*> result; char temp[16];//文字列Bの大きさ for(int i=0;i<file.size();i++){ strncpy(temp,&buffer[i],16); result.push_back(*temp); //次の文字列Bの位置までインデックスを移動//// while(buffer[i]!=0x0A){ i++; } i++; } }

みんなの回答

  • hitomura
  • ベストアンサー率48% (325/664)
回答No.2

「buffer って何?」とか「result.push_back(*temp); でコンパイルエラーにならないの?」とか言いたいことはいくつかありますが、 result.push_back(temp); だとして回答します(コンパイルが通るのはたぶんこれ)。 このコードで result に入るのは char temp[16]; で定義された temp へのポインタです。 その中に入った文字を result に入れたいのならば、std::string を使って vector<string> result; for(int i=0;i<file.size();i++){  string temp(buffer + i, buffer + i + 16);  result.push_back(temp);   … } とするか、 class FixStr {  char str[16 + 1]; public:  FixStr(const char* const instr)  {   if (instr){    strncpy(str, instr, 16);    str[16] = '\0';   } else {    str[0] = '\0';   }  }  FixStr(const FixStr& src)  {   strcpy(str, src.str);  }  FixStr& operator=(const FixStr& src)  {   if (src& != this) strcpy(str, src.str);   return *this;  }  const char* const GetStr() const  {   return str;  } }; というクラスを作って、 vector<FixStr> result; for(int i=0;i<file.size();i++){  result.push_back(FixStr(buffer + i));   … } とするかのどちらかでしょう。

  • mk48a
  • ベストアンサー率56% (1133/2007)
回答No.1

>char temp[16];//文字列Bの大きさ >result.push_back(*temp); tempはローカル変数で、そのアドレスをvectorに追加しています。 と、いうことは、同じ値を追加していることになります。 また、tempの中身が変われば(実際変わりますが)resultのvecotorの中身も変わっているように見えてしまいます。 vectorに追加する文字列の領域をnewで確保してから追加してください。 領域の開放も忘れずに。

関連するQ&A

  • VectorなどSTL?テンプレートの使い方

    戻り値がポインタの場合、関数から抜け出すと値の保証が無いので、それを使用する場合は、変数にコピーして使うと値は残る(アクセス可能)と理解しています。 char tmp[128]; strcpy(tmp, test()); それで、次のような vector??を使った場合、表示の場合は問題ないかもしれませんが、その後、値を使い続ける場合、ポインタのままでよいのか疑問に思っています。 以下のソースは勝手気ままに記述したものですが、 VC++6でエラーなく動作(とりあえず動く)しているのですが、今後発生する問題など知りたいです。 #include "stdafx.h" #include <string> #include <iostream> #include <vector> #include <sstream> using namespace std; class A { string str; vector<A *> v_cls; public: A(){ } // デフォルトコンストラクタが必要? A(string s){ str = s; } void PrintData(void){ // 表示 cout << str << endl; } // 1から9までの[0]-[9]の文字列を作成 vector<A *> ArraySet(void){ stringstream ss; for (int i=0; i < 10; i++){ ss.str(""); ss << "function [" << i << "]\n"; v_cls.push_back( new A( ss.str() ) ); } return v_cls; } }; void main(void){ // 1から9までの[0]-[9]の文字列を作成 // これは問題ないと思う vector<A *> v; stringstream ss; for (int i=0; i < 10; i++){ ss.str(""); ss << "[" << i << "]\n"; v.push_back( new A( ss.str() ) ); } v[1]->PrintData(); v[3]->PrintData(); ////cout << v.size(); // クラス自身にvector配列?を返す処理 // とりあえず動いているだけ??? A x; vector<A *> ret = x.ArraySet(); // このような代入でも問題ないのでしょうか? ret[5]->PrintData(); // 表示だけなので、問題なし? ret[0]->PrintData(); // vやret, xの解放仕方とタイミングはどうすればよいのでしょうか? }

  • C++ vector中のnewしたの文字列の削除の問題

    C++の新人ですが、困っている質問をさせていただきます。 C++のvectorの中にchar型の文字列を格納していて、どうやって、 memory leak が発生しないようにクリアしますか? たとえば、以下の例 std::vector<char *> vc; void pushvc(); int main(){ pushvc(); } void pushvc(){ char* a = new char[10]; char* b = new char[10]; a="sss"; b="bbb"; vc.push_back(a); vc.push_back(b); } よろしくお願いします。

  • C++ STL vectorの使い方

    こんばんは。 C++のstd::vectorに関する質問です。 vectorをポインタ渡しにしたときに メンバにアクセスする方法を知りたいのですが・・・ 以下ソースの☆の部分をどう記述したらよいでしょう? #include <vector> typedef struct test {  char name[10];  char id[2]; } TEST; void funcVectorTest( std::vector<TEST> *a); int main(){  std::vector<TEST> a;  int i;  TEST foo= {"Taro","0"};  a.push_back(foo);  printf("%s",a[0].name);  a.push_back(foo);  printf("%s",a[1].name);  funcVectorTest(&a);//vectorのアドレス渡しテスト  printf("%s", a[2].name);//vectorのアドレス渡し確認  return 0; } void funcVectorTest( std::vector<TEST> *a) {  int i;  int cnt;  TEST *b;  b = new TEST[3];  TEST foo= {"Taro","0"};  a->push_back(foo);  cnt = a->size();  for( i = 0; i < cnt;i++){  //以下でa[i]のnameにアクセスしたいのですがうまくいっていません。  //☆strcpy( b[i].name, a[i]->name );  }  delete[] b; } お分かりになる方、お知恵をお貸し下さい(><) vectorについて最近知ったばかりでいまいち使い方が 分かっていない部分があるので このやり方がまずいということであれば教えていただけると 助かります。 よろしくお願いしますm( _ _ )m

  • C言語について教えてください。

    #include <ctype.h> #include <stdio.h> void name_toupper(char istr[], char ostr[]) { unsigned i = 0; while (istr[i]) { ostr[i] = toupper(istr[i]); i++; } ostr[i] = '\0'; } void name_tolower(char istr[], char ostr[]) { unsigned i = 0; while (istr[i]) { ostr[i] = tolower(istr[i]); i++; } ostr[i] = '\0'; } void name_change(char istr[], char ostr[]) { unsigned i = 0; while (istr[i]) { if(isupper(istr[i])) { ostr[i] = tolower(istr[i]); } else { ostr[i] = toupper(istr[i]); } i++; } ostr[i] = '\0'; } int main(void) { char buffer[100]; char result[100]; printf("文字"); gets(buffer); name_toupper(buffer,result); printf("大文字: %s\n", result); name_tolower(buffer,result); printf("小文字: %s\n", result); name_change(buffer,result); printf("大小交換: %s\n", result); return 0; } 出力結果 文字abc DEFG 大文字: ABC DEFG 小文字: abc defg 大小交換: ABC defg 上のプログラムで文字関数isupperを用いずにプログラムする方法を教えてもらえませんか? もしくわ、用いずにプログラムすることは不可能ですか? 教えてください。 よろしくお願いします。

  • C言語 ソートについて

    #include <stdbool.h> #include <stdio.h> void swap(char *a, char *b) { } bool is_at(char c) { } void justify(char line[], int n) { } int main(void) { char line[] = "a@b@@@c@@d@@@ef@@g"; size_t n = sizeof(line) - 1; justify(line, n); printf("%s\n", line); return 0; } 上の雛形を使って文字列lineに含まれる@以外の文字を文字列の前の方に詰めていくプログラミングを作るという問題を解いていたのですが下のプログラミングまでは出来たのですが最後のjustifyの部分がわかりません 良ければ解答をお願いします #include <stdbool.h> #include <stdio.h> void swap(char *a, char *b) { char temp = *a; *a = *b; *b = temp; } bool is_at(char c) { if(c == '@') { return true; } else { return false; } } void justify(char line[], int n) { for(int i=0;i<n-1;i++) { } } int main(void) { char line[] = "a@b@@@c@@d@@@ef@@g"; size_t n = sizeof(line) - 1; justify(line, n); printf("%s\n", line); return 0; }

  • c言語 scanf

    下のソースを実行したらおかしなことになったんですがなんででしょうか?? #include<stdio.h> int main(void){ int i; char c[1000]; for(i=0;;i++){ printf("文字>>>>"); scanf("%c",&c[i]); printf("result = %c \n",c[i]); } } ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓実行↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 文字>>>>a result = a 文字>>>>result = 文字>>>>b result = b 文字>>>>result = 文字>>>>c result = c 文字>>>>result = 文字>>>>d result = d 文字>>>>result = 文字>>>>^C

  • 大文字を小文字に、小文字を大文字にするプログラム

    問題は、 ファイルにあるアルファベットの大文字を小文字に変換し、小文字は大文字に変換して、ファイルに保存するプログラムを作りなさい というものです。 色々考えて、 #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> int main(int argc,char **argv){ int fd,flag1,flag2; int i,n; char buffer[512],x; fd = open(argv[1],O_RDWR); if(fd == -1) perror("open"); while((n = read(fd,buffer,sizeof(buffer)))>0){ x = buffer[i]; flag1 = islower(x); flag2 = isupper(x); for(i=0;i<n;++i) if(flag1 == 1){ buffer[i] = toupper(buffer[i]); }else if(flag2 == 1){ buffer[i] = tolower(buffer[i]); } write(fd,buffer,n); } close(fd); exit(0); } のようなプログラムを考えましたが、うまくいきません。 toupperのような関数を使ったのは初めてなのでよく使い方が分からずこのようなプログラムになってしまいました。 どうか正しく動くようなプログラムを教えてください。お願いします。

  • 文字列を分解したいのですが・・・

    VC++初心者です。 ある文字列(数値、数値、数値CRLF数値、数値・・・)のような中からコンマで区切られた数字を取り出したいのですがうまくいきません。 とりあえずはコンマと改行コードの位置だけでも探したいのですがどうやったら良いでしょうか?お知恵を貸してください。 char buffer[64] = 10.52,5.88,4.37(改行コード)6.42,41.91; char* result; int ch1 = "CRLF"; result = strchr(buffer,ch1); int ch2 = "," result = strchr(buffer,ch2); 改行コードは最初の文字列に入ってるはずですが見えないので(改行コード)と入力しました。 よろしくお願いいたします。

  • fgetsで読み込んだ値のvector処理

    Visual C++ 2008でc++プログラミングの勉強をしています。 ファイルから文字列をfgetsで読み込み、vectorにいれる処理をプログラミングしようとしているのですが、うまくいきません。 input.txt------------------ sumday monday tuesday ------------------------- このような入力ファイルをfgetsで読み込み、各行を文字列としてvectorにpush_backし、 読み込みが終わった後にvectorの全要素をループで出力するというシンプルなものなのですが、以下のようにコーディングしました。 #include <stdio.h> #include <stdlib.h> #include <vector> int main(void){ using namespace std; FILE *fp; fp = fopen("input.txt","r"); std::vector<char *> my_vector; char buff[16]; while(fgets(buff, 256, fp) != NULL) { char copy_of_buff[16]; std::strcpy(copy_of_buff, buff); my_vector.push_back(copy_of_buff); printf("output from fgets..... %s \n", copy_of_buff); } vector<char *>::iterator it = my_vector.begin(); // while( it != my_vector.end() ) // { printf("output from vector.... %s \n", *it); ++it; // } fclose(fp); return 0; } 以下のような出力がなされるものと思っていたのですが、 outputs from fgets .... sunday outputs from fgets .... monday outputs from fgets .... tuesday output from vector .... sunday output from vector .... monday output from vector .... tuesday 実際は以下のように、vectorからの出力分がすべて最後にpush_backした"tuesday"となりました。 outputs from fgets .... sunday outputs from fgets .... monday outputs from fgets .... tuesday output from vector .... tuesday output from vector .... tuesday output from vector .... tuesday fgetsしたあとの処理が問題だと思うのですが、原因がよく分かりません。非常に基本的なことだと思うのですがwebで調べてもいまいちわかりません。 原因が分かる方、よろしくお願いします。

  • vectorを引数とする関数

    以下のようなプログラムにおいて、 #include <stdio.h> #include <cstdlib> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <map> using namespace std; double func(std::vector<double> *tmp2); int main(){ vector <double> tmp; tmp.resize(0); tmp.push_back(0.12458); tmp.push_back(-12.45); tmp.push_back(4.253); cout << func(&tmp) << endl; return 0; } double func(std::vector<double> *tmp2){ return tmp2[1]; } vector tmpをfuncに渡して、tmp[1]、すなわち、 -12.45が出力されるようにしたいと思います。 ですが、どうしてもコンパイルエラーが残ります。 どのようにすればよいでしょうか?

専門家に質問してみよう