0

文字列を配列に格納するコードを作成しようとしています。char* でやろうとしていますが、達成できませんでした。ネットを検索しましたが、答えが見つかりませんでした。以下のコードを試しましたが、コンパイルできませんでした。ある時点で文字列と整数を連結する必要があるため、文字列ストリームを使用します。

stringstream asd;
asd<<"my name is"<<5;
string s = asd.str();
char *s1 = s;
4

5 に答える 5

5

> 文字列を配列に格納するコードを書こうとしています。

まず、文字列の配列が必要です。裸の配列を使用するのは好きではないので、次を使用しますstd::vector

std::vector<std::string> myStrings;

ただし、配列を使用する必要があることは理解しているので、代わりに配列を使用します。

// I hope 20 is enough, but not too many.
std::string myStrings[20];
int j = 0;

> 文字列ストリームを使用する理由は ...

さて、stringstream を使用します。

std::stringstream s;
s << "Hello, Agent " << 99;
//myStrings.push_back(s.str()); // How *I* would have done it.
myStrings[j++] = s.str(); // How *you* have to do it.

これで1 つの文字列が得られますが、それらの配列が必要です。

for(int i = 3; i < 11; i+=2) {
  s.str(""); // clear out old value
  s << i << " is a" << (i==9?" very ":"n ") << "odd prime.";
  //myStrings.push_back(s.str());
  myStrings[j++] = s.str();
}

これで、文字列の配列ができました。

テスト済みの完全なプログラム:

#include <sstream>
#include <iostream>

int main () {
  // I hope 20 is enough, but not too many.
  std::string myStrings[20];
  int j = 0;

  std::stringstream s;
  s << "Hello, Agent " << 99;
  //myStrings.push_back(s.str()); // How *I* would have done it.
  myStrings[j++] = s.str(); // How *you* have to do it.

  for(int i = 3; i < 11; i+=2) {
    s.str(""); // clear out old value
    s << i << " is a" << (i==9?" very ":"n ") << "odd prime.";
    //myStrings.push_back(s.str());
    myStrings[j++] = s.str();
  }

  // Now we have an array of strings, what to do with them?
  // Let's print them.
  for(j = 0; j < 5; j++) {
    std::cout << myStrings[j] << "\n";
  }
}
于 2012-04-07T20:50:04.067 に答える
2

このようなものはどうですか?

vector<string> string_array;
stringstream asd;
asd<<"my name is"<<5;
string_array.push_back(asd.str());
于 2012-04-07T20:47:29.993 に答える
1
char *s1 = s;

違法です。次のいずれかが必要です。

const char *s1 = s.c_str();

に設定されていない場合、または文字列からコンテンツをコピーするためにchar*new を割り当ててchar*使用する必要があります。strcpy

于 2012-04-07T20:46:38.640 に答える
0

コードを次のように変更するだけです

char const* s1 = s.c_str();

char へのポインタは文字列オブジェクトを格納できず、c_str() が返すものである char へのポインタのみを格納できるためです。

于 2012-04-07T20:46:58.850 に答える
0

char * を直接使用しません。以下のテンプレートのようなものでラップします。さらに操作を行うために必要な演算子をオーバーライドできます (たとえば、data をプライベート メンバーにし、演算子をオーバーライドして、データがきれいに出力されるようにします)。私が代入演算子を使ったのは、それがいかにきれいなコードを作成できるかを示すためだけでした。

#include "MainWindow.h"

#include <stdio.h>

using namespace std;

template<size_t size>
class SaferChar
{
public:

  SaferChar & operator=(string const & other)
  {
    strncpy(data, other.c_str(), size);

    return *this;
  }

  char data[size];
};

int main(int argc, char *argv[])
{
  SaferChar<10> safeChar;
  std::string String("Testing");


  safeChar = String.c_str();

  printf("%s\n", safeChar.data);

  return 0;
}
于 2012-04-07T21:19:10.040 に答える