About usage of << operator [Resolved]


#1

this is the comment for String::formated method:


/** Creates a String from a printf-style parameter list.
        I don't like this method. I don't use it myself, and I recommend avoiding it and
        using the operator<< methods or pretty much anything else instead. It's only provided
        here because of the popular unrest that was stirred-up when I tried to remove it...
        If you're really determined to use it, at least make sure that you never, ever,
        pass any String objects to it as parameters. And bear in mind that internally, depending
        on the platform, it may be using wchar_t or char character types, so that even string
        literals can't be safely used as parameters if you're writing portable code.
    */

could anyone tell me how to use << for string?

I always use String::formated("%.1f", myFloatVal); to convert float value into string.

so anyone could tell me how to use << operator to achive the same target?

I only use << operator for inputstream / ouputstream instance.

thank you.

 


#2
String::formatted ("%.1f", myFloatVal);

is the same as

float   myFloatVal  = 1.234f;
        
String szStringObject (myFloatVal, 1);
        
DBG ("          szStringObject = " + szStringObject);
        
DBG ("szStringObject.formatted = " << szStringObject.formatted ("%.1f", myFloatVal));

will output:

Check out operator<< in the String class to see how you can use the << operator to concatenate simple String objects.

Rail


#3

You seem a little confused yourself there, Rail! formatted() is a static method.

Let me rewrite your example in a slightly clearer way:

float myFloatVal = 1.234f;

// These will print the same thing:        
DBG (String (myFloatVal, 1));
DBG (String::formatted ("%.1f", myFloatVal));

 


#4

Thanks guys, actually Jules's comment confused me:

"I don't like this method. I don't use it myself, and I recommend avoiding it and using the operator<< methods or pretty much anything else instead."

i originally thought that i could use it like this:

String() << "..." << String(5.55f, 1) << newLine;

 


#5

That's true - I don't like or recommend using formatted(), for the same reasons that people advise against printf nowadays.

And yes, of course you can use it to write to a String just like you'd write to an OutputStream, although your example code is trying to append to a temporary string, which doesn't make much sense. You'd do:

String s;

s << "..." << String(5.55f, 1) << newLine;

DBG (s);

There are thousands of examples of this kind of thing in the codebase.


#6

got it, thanks!