开发者

Why is my string not being printed?

开发者 https://www.devze.com 2023-02-08 10:55 出处:网络
I have some code that, in its smallest complete form that exhibits the problem (being a good citizen when it comes to asking questions), basically boils down to the following:

I have some code that, in its smallest complete form that exhibits the problem (being a good citizen when it comes to asking questions), basically boils down to the following:

#include <string>
#include <iostream>
int main (void) {
    int x = 11;
    std::string s = "Value was: " + x;
    std::cout << "[" <开发者_运维知识库< s << "]" << std::endl;
    return 0;
}

and I'm expecting it to output

[Value was: 11]

Instead, instead of that, I'm getting just:

[]

Why is that? Why can I not output my string? Is the string blank? Is cout somehow broken? Have I gone mad?


"Value was: " is of type const char[12]. When you add an integer to it, you are effectively referencing an element of that array. To see the effect, change x to 3.

You will have to construct an std::string explicitly. Then again, you cannot concatenate an std::string and an integer. To get around this you can write into an std::ostringstream:

#include <sstream>

std::ostringstream oss;
oss << "Value was: " << x;
std::string result = oss.str();


You can't add a character pointer and an integer like that (you can, but it won't do what you expect).

You'll need to convert the x to a string first. You can either do it out-of-band the C way by using the itoa function to convert the integer to a string:

char buf[5];
itoa(x, buf, 10);

s += buf;

Or the STD way with an sstream:

#include <sstream>

std::ostringstream oss;
oss << s << x;
std::cout << oss.str();

Or directly in the cout line:

std::cout << text << x;


Amusing :) That's what we pay for C-compatibility and the lack of a built-in string.

Anyway, I think the most readable way to do it would be:

std::string s = "Value was: " + boost::lexical_cast<std::string>(x);

Because the lexical_cast return type is std::string here, the right overload of + will be selected.


C++ doesn't concatenate strings using the the + operator. There's also no auto-promote from data types to string.


In C/C++, you cannot append an integer to a character array using the + operator because a char array decays to a pointer. To append an int to a string, use ostringstream:

#include <iostream>
#include <sstream>

int main (void) {  
  int x = 11;
  std::ostringstream out;
  out << "Value was: " << x;
  std::string s = out.str();
  std::cout << "[" << s << "]" << std::endl;
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消