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?
using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);
A string is something that you can use to make words in without vars. A print is a function that prints a string, number and or variables. string is an variable and stores text , on the other hand print gives the output of string or output of parameter written in it.
C program to read and print string using scanf and printf This program first takes a string as input from user using scanf function and stores it in a character array inputString. It automatically adds a null terminating character at the end of input string. Then it uses printf function to print inputString on screen.
"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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With