Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my string not being printed?

Tags:

c++

string

std

cout

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?

like image 997
paxdiablo Avatar asked Feb 03 '11 06:02

paxdiablo


People also ask

How can I print a string?

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);

What is the difference between print and string?

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.

How strings are read and printed?

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.


1 Answers

"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();
like image 67
Oswald Avatar answered Sep 22 '22 05:09

Oswald