文字列を配列に格納するコードを作成しようとしています。char* でやろうとしていますが、達成できませんでした。ネットを検索しましたが、答えが見つかりませんでした。以下のコードを試しましたが、コンパイルできませんでした。ある時点で文字列と整数を連結する必要があるため、文字列ストリームを使用します。
stringstream asd;
asd<<"my name is"<<5;
string s = asd.str();
char *s1 = s;
> 文字列を配列に格納するコードを書こうとしています。
まず、文字列の配列が必要です。裸の配列を使用するのは好きではないので、次を使用します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";
}
}
このようなものはどうですか?
vector<string> string_array;
stringstream asd;
asd<<"my name is"<<5;
string_array.push_back(asd.str());
char *s1 = s;
違法です。次のいずれかが必要です。
const char *s1 = s.c_str();
に設定されていない場合、または文字列からコンテンツをコピーするためにchar*
new を割り当ててchar*
使用する必要があります。strcpy
コードを次のように変更するだけです
char const* s1 = s.c_str();
char へのポインタは文字列オブジェクトを格納できず、c_str() が返すものである char へのポインタのみを格納できるためです。
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;
}