1

I'm trying to control the number of Digits i add in a String , but I couldn't control it since i am printing an Array of Strings .

float loads[n] = { 1,2,3,0.05,1,2,3,0.5,1,2,3,3,1,2 };
string print[nBits] = { "" };
int n=14;
int BB;
.
.
.
void main(){
 for (int j = 0; j < nBits; ++j)// 2^n
   {     
         for (int i = 0; i < n; ++i) // n
        {
            BB = arr[j][i];
            R = loads[i];
            if (BB == 1) {
            print[j]+="" +std::to_string(loads[i])+"//";
        }
   }
}

But i eventually get an Array of strings that Looks like this :

0.050000//3.000000//...

Is there any way to control the Precision of the floating number before adding it to the String ?

(so i can have a resulting string control a fixed number of Digits instead)

0.05//3.00// ...

1

2 Answers 2

3

Use std::stringstream together with std::fixed and std::setprecision(n).

http://en.cppreference.com/w/cpp/io/manip

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the standard streaming mechanic:

streams

You can use ostream to generate the string:

#include <ostream>
#include <sstream>
#include <iomanip>

std::ostringstream stream;
for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

The idea is to generate a stream that you can stream strings too. You can then generate a std::string out of it, using stream.str(). Streams have default values for how to convert numbers. You can influence this with std::setprecision and std::fixed as well as other variables (for more info, see the C++ stdlib reference).

Using std::setprecision and std::fixed.

std::ostringstream stream;
// set the precision of the stream to 2 and say we want fixed decimals, not
// scientific or other representations.
stream << std::setprecision(2) << std::fixed;

for(...) {
   stream << loads[i] << "//";
}
std::string str =  stream.str();

You find another example here.

sprintf

You can always go the C way and use sprintf although it's discouraged as you have to provide a buffer of correct length, e.g.:

char buf[50];
if (snprintf(buf, 50, "%.2f", loads[i]) > 0) {
   std::string s(buf);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.