So I have a function below formatted as polymorphic void display(string& outStr). The output from this function should basically be formatted into one large string, which will be saved to the outStr parameter and returned to the calling function.
I have successfully formatted my large string into multiple lines but I would like to round my float value to 2 decimal places but I can't figure out how with the way I'm currently appending my strings. I tried using the round() and ceil() functions as some posts online have suggested, but 6 zeros still appear after each decimal place. I would appreciate some help with this as I've been looking for solutions for a while but none of them have worked.
Additionally, I was wondering if the to_string() function I used to convert my float to a string would compile and execute correctly in C++98? I'm using C++11 but my teacher is using C++98 and I'm extremely worried that it won't compile on her end.
If not, can anyone suggest how else I could achieve the same result of turning a float into a string while still formatting multiple lines into the outStr string parameter and returning it to the function? I am not allowed to change the function's parameters, it must stay as display(string& outStr)
My output is a lot longer and complex but I simplified the example for the sake of getting a short and easy solution.
Again, I would appreciate any help!
#include <iostream>
using namespace std;
#include <string>
#include <sstream>
#include <cmath>
#include "Math.h"
void Math::display(string& outStr){
float numOne = 35;
float numTwo = 33;
string hello = "Hello, your percent is: \n";
outStr.append(hello);
string percent = "Percent: \n";
outStr.append(percent);
float numPercent = ceil(((numOne / numTwo) * 100) * 100.0) / 100.0;
outStr.append(to_string(numPercent));
outStr.append("\n");
}
Output should look like:
Hello, your percent is:
Number:
106.06%
There is no need to do any crazy conversions. Since the function is called display, my guess is that it's actually supposed to display the value instead of just save it to a string.
The following code demonstrates how that can be accomplished by just formatting your printing.
#include <cstdio>
#include <iomanip>
#include <iostream>
int main() {
double percentage = 83.1415926;
std::cout << "Raw: " << percentage << "%\n";
std::cout << "cout: " << std::fixed << std::setprecision(2) << percentage << "%\n";
printf("printf: %.2f\%%\n", percentage); // double up % to print the actual symbol
}
Output is:
Raw: 83.1416%
cout: 83.14%
printf: 83.14%
If the function is as backwards as you describe it, there are two possibilities. You don't understand what's actually required and are giving us a bad explanation (my guess given that function signature), or the assignment itself is pure garbage. As much as SO likes to rag on professors, I find it difficult to believe that what you've described and written is what the professor wants. It makes no sense.
A couple notes: there is nothing polymorhpic about the code you've shown. to_string() exists as of C++11, which is easily seen by looking up the function (Link). There is also a discrepancy between what your code attempts to print versus what your output is, and that's before we even get to the number formatting portion. "Percent" or "Number"?
Related
I am a beginner in C++, started last week. I am trying to make a simple program converting a number of inches to foot inch notation: E.g. 62 turns into 5'2". However when I try to compile I have some error in line 8. I don't know what it is. Thanks in advance.
#include <iostream>
#include <sstream>
using namespace std;
string ConvertToFootInchMeasure (int totalInches){
string feet = ""+totalInches/12;
string inches = "" + totalInches%12;
stringstream converted;
conveted<<feet;
converted<<"'";
converted<<inches;
converted<<"\"";
return converted.str();
}
That code can be easily fixed like this:
string ConvertToFootInchMeasure (int totalInches){
stringstream converted;
// Do inline calculations and use formatted text output for the results
converted << (totalInches/12) << "'" << (totalInches%12) << "\"";
return converted.str();
}
To explain further: You tried to concatenate the numeric results of the totalInches/12 and totalInches%12 operations to a std::string variable, but the right side of the statement doesn't do that.
Note:
std::string operator+(std::string, char c) doesn't do conversion of numerics to string and concatenation as you tried to use with:
string feet = ""+totalInches/12;
also it seems to be even worse in your case because the term
""+totalInches/12
does pointer arithmetics for a const char* pointer, and the string variable is initialized from e.g. a pointer address "" + (62/12).
I am trying to convert a string based number to float. Unfortunately I am getting either the rounded off value or truncated value. How can I fix this.
std::string text = "199102.92";
float v = std::stof(text);
std::cout<<v<<std::endl;
This results in 199103
Even if I use setprecision and fixed then it only affects the output stream but the value passed into the float variable remains 199103. How can i resort this problem.
I have also used stringstream in c++ but results seem to be the same except it just displays off well.
I need to preserve the decimal upto 2 places.
I have used stof,stod, they all do the same thing.
You may assume that I am working with currencies.
I assume that you use std::setprecision and std::fixed incorrectly.
Following works for me:
#include <iostream>
#include <iomanip>
#include <string>
string text = "199102.92";
float v = std::stof(text);
std::cout << std::setprecision(2) << std::fixed << v << std::endl;
The result is 199102.92
Compiler info: g++ 5.4.0, --std=c++11.
I am new to C++, learning it by my self, and I am using the book "C++ how to program - 7th edition" from Deitel. Now, please have a look at the following code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double principle = 1000;
double amount;
double rate = 0.05;
cout << "Year" << setw(21) << "Amount on deposit" << endl;
cout << fixed << setprecision(2);
for(int years=1; years<=10; years++)
{
amount = principle * pow(1.0+rate,1.0);
cout << setw(4) << years << setw(21) << amount << endl;
}
}
When I removed the "fixed" stream manipulator, the output becomes stupid, which means, just ascii letters and numbers. When I insert it, the output comes without any problem. My question is, why is this happening? Is "fixed" mandatory for all the programs which has "double" type outputs? Please help.
And another thing. What are stream manipulators? As a Java developer, I thought these might be some kind of constant variables, but it is not! They are methods? Then why the brackets are not there? Please answer to this question too.
Thanks
The output does not "become stupid": you simply let your output stream choose the format for your floating-point numbers, and it picks scientific notation. This gives you 1e+03 (which means 1*10^3) instead of 1050.00. The use of fixed tells the stream that you do not want scientific notation; you could also use scientific to force the scientific format. Since the precise format depends depends on your application requirements, the choice to use fixed or scientific is ultimately up to you.
Manipulators like fixed are functions, but if you wanted the common () for it then it would look like this:
fixed(cout); //Instead of using the << or >> you pass the stream into the manipulator function.
See this reference for more on manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/
Also, fixed documentation can be found here:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
Hope this helps
It's not just ascii letter and numbers
1e+03 is scientific writing for 1*10^3 which is 1000
for reference:
http://www.cplusplus.com/reference/iostream/manipulators/fixed/
If you had chose a wider precision, your output would have been different without fixed.
cout << setprecision(6); // 6 instead of 2
Then your output would have looked more like you expected. (Incidentally, you should compute the compound interest by folding the interest earned back into the principle.)
Otherwise, with only setprecision(2), the formatter decides to use scientific notation in order to only display 2 digits of precision.
But, since you want the output to provide a fixed number of digits, what you have provided (both fixed and setprecision(2)) will do that.
I am very new to C++ and I am wondering how you output/write variables declared as double to a txt file. I know about how to output strings using fstream but I cant figure out how to send anything else. I am starting to think that you can't send anything but strings to a text file is that correct? If so then how would you convert the information stored in the variable to a string variable?
Here is my code that I'm trying to implement this concept into, Its fairly simple:
int main()
{
double invoiceAmt = 3800.00;
double apr = 18.5; //percentage
//compute cash discount
double discountRate = 3.0; //percentage
double discountAmt;
discountAmt = invoiceAmt * discountRate/100;
//compute amount due in 10 days
double amtDueIn10;
amtDueIn10 = invoiceAmt - discountAmt;
//Compute Interest on the loan of amount (with discount)for 20 days
double LoanInt;
LoanInt = amtDueIn10 * (apr /360/100) * 20;
//Compute amount due in 20 days at 18.5%.
double amtDueIn20;
amtDueIn20 = invoiceAmt * (1 + (apr /360/100) * 20);
return 0;
}
So what I'm trying to do is use those variables and output them to the text file. Also please inform me on the includes that I need to use for this source code. Feel free to give suggestions on how to improve my code in other ways as well please.
Thanks in advance.
As your tagging suggests, you use file streams:
std::ofstream ofs("/path/to/file.txt");
ofs << amtDueIn20;
Depending on what you need the file for, you'll probably have to write more stuff (like whitespaces etc.) in order to get decent formatting.
Edit due to rmagoteaux22's ongoing problems:
This code
#include <iostream>
#include <fstream>
const double d = 3.1415926;
int main(){
std::ofstream ofs("test.txt");
if( !ofs.good() ) {
std::cerr << "Couldn't open text file!\n";
return 1;
}
ofs << d << '\n';
return 0;
}
compiles for me (VC9) and writes this to test.txt:
3.14159
Can you try this?
Simply use the stream write operator operator<< which has an overloaded definition for double (defined in basic_ostream)
#include <fstream>
...
std::fstream stmMyStream( "c:\\tmp\\teststm.txt", std::ios::in | std::ios::out | std::ios::trunc );
double dbMyDouble = 23.456;
stmMyStream << "The value is: " << dbMyDouble;
To answer your first question, in C you use printf (and for file output fprintf). IIRC, cout has a large number of modifiers also, but I won't mention them as you originally mentioned fstream (more 'C' centric than C++) --
oops, missed the ofstream indicator, ignore my 'C' comments and use C++
to improve your program, be sure to use parentheses a lot when doing computations as above to be 100% sure things are evaluated the way you want them to be (do not rely on order of precedence)
Generally speaking methods to write to a output are printf, wprintf etc.
In case of files, these methods are named as fprintf_s, fsprintf_s etc.
Note that the '_s' methods are the new secure variations of previous formatting methods. You should always use these new secure versions.
For examples refer to:
http://msdn.microsoft.com/en-us/library/ksf1fzyy%28VS.80%29.aspx
Note these methods use a format specifier to convert a given type to text. For example %d acts as a place holder for integer. Similarly %f for double.
Just use the << operator on an output stream:
#include <fstream>
int main() {
double myNumber = 42.5;
std::fstream outfile("test.txt", std::fstream::out);
outfile << "The answer is almost " << myNumber << std::endl;
outfile.close();
}
I was having the exact same problem, where ofstream was outputting strings, but stopped as soon as it reached a variable. With a bit more Googling I found this solution in a forum post:
Under Xcode 3.2 when creating a new project based on stdc++ project template the target build settings for Debug configuration adds preprocessor macros which are incompatible with gcc-4.2:
_GLIBCXX_DEBUG=1
_GLIBXX_DEBUG_PEDANTIC=1
Destroy them if you want Debug/gcc-4.2 to execute correctly.
http://forums.macrumors.com/showpost.php?p=8590820&postcount=8
I am trying to manipulate a string in C++. I am working with an Arduino board so I am limited on what I can use. I am also still learning C++ (Sorry for any stupid questions)
Here is what I need to do:
I need to send miles per hour to a 7 segment display. So if I have a number such as 17.812345, I need to display 17.8 to the 7 segment display. What seems to be most efficient way is to first multiply by 10 (This is to shift the decimal point right one place), then cast 178.12345 to an int (to chop decimal points off). The part I am stuck on is how to break apart 178. In Python I could slice the string, but I can't find anything on how to do this in C++ (or at least, I can't find the right terms to search for)
There are four 7 segment displays and a 7 segment display controller. It will measure up to tenths of a mile per hour. Thank you very much for an assistance and information you can provide me.
It would probably be easiest to not convert it to a string, but just use arithmetic to separate the digits, i.e.
float speed = 17.812345;
int display_speed = speed * 10 + 0.5; // round to nearest 0.1 == 178
int digits[4];
digits[3] = display_speed % 10; // == 8
digits[2] = (display_speed / 10) % 10; // == 7
digits[1] = (display_speed / 100) % 10; // == 1
digits[0] = (display_speed / 1000) % 10; // == 0
and, as pointed out in the comments, if you need the ASCII value for each digit:
char ascii_digits[4];
ascii_digits[0] = digits[0] + '0';
ascii_digits[1] = digits[1] + '0';
ascii_digits[2] = digits[2] + '0';
ascii_digits[3] = digits[3] + '0';
This a way you can do it in C++ without modulus math (either way seems fine to me):
#include "math.h"
#include <stdio.h>
#include <iostream.h>
int main( ) {
float value = 3.1415;
char buf[16];
value = floor( value * 10.0f ) / 10.0f;
sprintf( buf, "%0.1f", value );
std::cout << "Value: " << value << std::endl;
return 0;
}
If you actually want to be processing this stuff as strings, I would recommend looking into stringstream. It can be used much the same as any other stream, such as cin and cout, except instead of sending all output to the console you get an actual string out of the deal.
This will work with standard C++. Don't know much about Arduino, but some quick googling suggests it won't support stringstreams.
A quick example:
#include <sstream> // include this for stringstreams
#include <iostream>
#include <string>
using namespace std; // stringstream, like almost everything, is in std
string stringifyFloat(float f) {
stringstream ss;
ss.precision(1); // set decimal precision to one digit.
ss << fixed; // use fixed rather than scientific notation.
ss << f; // read in the value of f
return ss.str(); // return the string associated with the stream.
}
int main() {
cout << stringifyFloat(17.812345) << endl; // 17.8
return 0;
}
You can use a function such as this toString and work your way up from there, like you would in Python, or just use modulo 10,100,1000,etc to get it as numbers. I think manipulating it as a string might be easier for you, but its up to you.
You could also use boost::lexical_cast, but it will probably be hard to get boost working in an embedded system like yours.
A good idea would be to implement a stream for the display. That way the C++ stream syntax could be used and the rest of the application would remain generic. Although this may be overkill for an embedded system.
If you still want to use std::string you may want to use a reverse iterator. This way you can start at the right most digit (in the string) and work towards the left, one character at a time.
If you have access to the run-time library code, you could set up a C language I/O for the display. This is easier to implement than a C++ stream. You could then use fprint, fputs to write to the display. I implemented a debug port in this method, and it was easier for the rest of the developers to use.