2

send() に挿入変数を追加しようとしています。

コードは次のとおりです。

string num;

// + num + is the reason for the error. Any work around or suggestions?
char *msg = "GET /index.php?num=" + num + " HTTP/1.1\nhost: domain.com\n\n";

int len;
ssize_t bytes_sent;
len = strlen(msg);
bytes_sent = send(socketfd, msg, len, 0);

エラーが発生します:

test.cpp: In function âint main()â:
test.cpp:64: error: cannot convert âstd::basic_string<char, std::char_traits<char>, 
std::allocator<char> >â to âchar*â in initialization

- 編集 -

msg.c_str で修正しようとしました

cout << "send()ing message..."  << endl;
string msg = "GET /index.php?num=" + num + " HTTP/1.1\nhost: domain.com\n\n";   
int len;
ssize_t bytes_sent;
len = msg.lenght(); //updated to this and still gives me an error.
bytes_sent = send(socketfd, msg.c_str, len, 0);

今、それは私にエラーを与えます:

error: argument of type âconst char* (std::basic_string<char, std::char_traits<char>, 
std::allocator<char> >::)()constâ does not match âconst char*â
4

4 に答える 4

3

"stuff" + num + "more stuff"あなたが期待することをしません。char ポインターに変換strしたとしても、C++ で char ポインターを一緒に追加できるとしても、まったく間違ったことをすることになります。

(参考までに、C++ではポインターを一緒に追加することはできません。結果が意味をなさないためです。ポインターはまだ単なる数値であり、2 つの char ポインターを追加すると、基本的に、0x59452448 + 0x10222250またはそのようなものになり、ポインターが返されます。おそらくまだ存在すらしていない場所へ...)

これを試して:

string msg = string("GET /index.php?num=") + num + " HTTP/1.1\nhost: domain.com\n\n";
ssize_t bytes_sent = send(socketfd, msg.c_str(), msg.size(), 0);
于 2012-11-25T21:50:44.673 に答える
1

std::string暗黙的にに変換されませんchar*。を使用する必要がありますc_str

于 2012-11-25T21:45:37.227 に答える
1

num3行目の初期化されていない場所を使用しています。多分あなたがしたい:

std::string num;
std::string msg = "GET /index.php?num=" + num + " HTTP/1.1\nhost: domain.com\n\n";
于 2012-11-25T21:43:53.147 に答える
1

理想的には、API 関数が char* を必要とするポイントまで、アプリケーションで文字列 (char* ではなく) を完全に操作し、その時点でc_str文字列を呼び出して、関数の const char* を取得する必要があります。呼んでいます。

于 2012-11-25T21:48:38.187 に答える