How to round a number to the nearest hundreath and make that display on a string in c++ - string

I am working on a money program. Currently I am trying to make a part in the program that displays a list that shows every transaction that was made in the session. My problem is that when I convert the money amount to a string instead of displaying something like 100.35 in when converted to a string it instead displays something like 100.35000000. I was wondering if there was any way I could make the program drop the additional zeros? Here is a sample of how I convert the numbers to a string
int main(){
double samplemoney=100.35;
string sample="Today we made $";
string comsample;
comsample=sample+std::tostring(money)+".";
cout<<comsample<<endl;
return 0;
}
In my main program this part is handled with a class but as I said earlier it seems like no matter what the money value I put in is it will display a series of zero and I want my program to drop the unnecessary zeros.

Let's say you have this number:
double number = 190.0391000;
If the problem is displaying the value you may use
std::cout << std::setprecision(5) << number
where f is the number you want to show.
If your problem is having a string with a finite precision you can use sprintf() in the following way:
char arr[128];
sprintf(arr,"%3.2f", number);
std::string formattedstring(arr);
or in a more C++ oriented way something like this
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
and then you get the string in the following way:
std::string formattedstring = strn.str();
I attach the full text of program here... tested on my machine:
#include <sstream>
#include <iostream>
int main() {
float number=100.24324232;
std::stringstream strn;
strn.precision(2);
strn << std::fixed << number;
std::cout << strn.str() << "\n";
return( 0 );
}

Related

How do I convert strings of numbers, coming from a .txt file into an int array using stoi::("string")

I've been trying to take a .txt document with three number entries, read those entries as strings and convert those entries in ints, then put them into an int array, but had no success in doing so and i have no clue as to why. Note that the entries as well as some variable names are pre determined by the assignment, additionally we have to use the std::stoi("string") command, which i am not familiar with nor has any syntax been provided to us (which is especially strange since we are usually not allowed to stray to far from the lecture material)
What I excpected to happen is that the numbers from the .txt file were converted into an array, however what actually happened is that an "unhandled exception" (my apologies if that term does not make sanes we have to programm in our native language) occured and the string library opened itself, marking the error on line 107. The problematic line in my code seems to be "auftraegearray[i++] = std::stoi(MengeanAuftraegen);"
int main()
{
std::fstream Auftraege;
Auftraege.open("Auftraege37.txt", std::ios::out);
Auftraege << "10" << std::endl;
Auftraege << "1" << std::endl;
Auftraege << "20" << std::endl;
Auftraege.close();
int i = 0;
int auftraegearray[4];
std::string MengeanAuftraegen;
Auftraege.open("Auftraege37.txt", std::ios::in);
while (!Auftraege.eof())
{
getline(Auftraege, MengeanAuftraegen);
std::cout << MengeanAuftraegen << std::endl;
auftraegearray[i++] = std::stoi(MengeanAuftraegen);
}
Auftraege.close();

Why doesn't string class take in two words separated with space?

I want to take in persons name using string object. But in my code if I put two part name separated with a space, only first part is displayed. My understanding is .c_str() returns a pointer to stored string with terminal null. Why is there a problem with space. I'm new to C++ and using Code::Blocks 13.12. This is a simplified version of the problem that I have in another program that I wrote.
Thanks in advance.
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string sCusName;
cout << "Please enter your name-> ";
cin >> sCusName;
int xsize = sCusName.length();
char *tempBuffer = new char[xsize+1];
strncpy(tempBuffer, sCusName.c_str(),xsize+1);
cout << tempBuffer << " is a beautiful name." << endl;
return 0;
}
When I enter single part name, program works fine. But if I put in two part name separated with space. Only first part is taken in.
it is not possible to read multi-word string using cin rather you should use getline() the getline() function takes two arguments cin and string variable forexample:
int main()
{
string sCusName;
cout << "Please enter your name-> ";
getline(cin,sCusName);
cout << sCusName << " is a beautiful name." << endl;
return 0;
}

How to make an array of pointers and make the user enter the size of it?

I want to make an array, and inside this array there are pointers, like this:
int *arrp[size]; and I want the user to enter the size of it.
I tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int *arrp[size];
return 0;
}
but this doesn't work.
I also tried to do this:
#include <iostream>
using namespace std;
int main ()
{
int size;
cout << "Enter the size of the array of pointers" << endl;
cin >> size;
int* arrp[] = new int[size];
return 0;
}
also doesn't work, can someone help?
The error of the first code is that the size must be constant, I tried to fix that by writing the 2nd code but it gives an error for the word "new" in line 9:
E0520 initialization with '{...}' expected for aggregate object
and another error for the size in the same line:
C2440 'initializing': cannot convert from 'int *' to 'int *[]'
To make an array of pointers you should type: int** arr = new int*[size]
we type 2 stars '*', the first mean a pointer to an integer, the second means a pointer to the pointer to the integer, and then we make a place in the memory for those pointers by typing = new int*[size], you can use this as a 2D array that stored in the heap (not the stack) go to this website to know the difference: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/.
to know more about how to use an array of pointers to a pointer to an integers you can see this video: https://www.youtube.com/watch?v=gNgUMA_Ur0U&ab_channel=TheCherno.

string to boost::uuid conversion

I've just started using boost in c++ and I just wanted to ask a couple of questions relating to uuids.
I am loading in a file which requires I know the uuids so I can link some objects together. For this reason, I'm trying to write my own uuids but I'm not sure if there's any special conditions for the strings etc as the strings I've been using (usually something basic) are not working. Can anyone point me in the right direction? I've tried using a string generator, but to no avail thus far so I'm assuming there's something wrong with my strings (which have currently just been random words).
Here's a short example kind of thing, can't give the real code:
void loadFiles(std::string xmlFile);
void linkObjects(custObj network)
{
for (int i = 0; i < network->getLength(); i++)
{
network[i]->setId([boost::uuid]);
if (i > 0)
network[i]->addObj(network[i-1]->getId());
}
}
I took your question as "I need a sample". Here's a sample that shows
reading
writing
generating
comparing
uuids with Boost Uuid.
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/lexical_cast.hpp>
using namespace boost::uuids;
int main()
{
random_generator gen;
for (int i = 0; i < 10; ++i)
{
uuid new_one = gen(); // here's how you generate one
std::cout << "You can just print it: " << new_one << "; ";
// or assign it to a string
std::string as_text = boost::lexical_cast<std::string>(new_one);
std::cout << "as_text: '" << as_text << "'\n";
// now, read it back in:
uuid roundtrip = boost::lexical_cast<uuid>(as_text);
assert(roundtrip == new_one);
}
}
See it Live On Coliru

how to convert mpf_class to String

Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.
Basically what I did was:
std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));
As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks
Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.
Here is my code
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
int main(void) {
mpf_class a;
a = 3141592653589793.2;
std::cout << a << std::endl;
// Outputs 3.14159e+15
std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
// Outputs +3.14E+15
}
Then you can use an std::ostringstream object instead of std::cout.
Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html

Resources