String to float conversion and formatting - c++

Currently I have something like this
float a = SomeQString.toFloat(); //QString has 2.37
Now float is 2.3690000031..
What I want is 2.3700000000.. any suggestion on how i could do that ? Also why am i getting 2.369 instead of 2.37?

(Has been asked and explained so many times.) It is not possible to get 2.37 in a float. It is not possible to get 2.37 in a double. It is not possible to get 2.37 in any IEEE-754 style binary floating-point format. 2.37 is not representable precisely in such binary floating-point formats.
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic
One viable way to "obtain" 2.37 is actually to store that 2.369... in a float (which is what you do already) and then round it to 2.37 at the time when you'll need to generate the decimal representation, i.e. at the time when you have to present/output the value to the user.

#include <string>
#include <sstream>
int main(void)
{
std::string QString = "2.37";
std::istringstream StrToFloat(QString );
float floatVar;
StrToFloat >> floatVar;
return 0;
}

If you insist on using Qt, this is the appropriate code for you:
#include <QString>
#include <QTextStream>
#include <QDebug>
using namespace std;
int main()
{
QString floatString = "2.37";
QTextStream floatTextStream(&floatString);
float f;
floatTextStream >> f;
qDebug() << f;
return 0;
}
Run the following command with gcc for instance, and Qt 5 (or something similar if you have a different scenario):
Command: g++ -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core -fPIC main.cpp && ./a.out
Output: 2.37
However, You do not need QString for doing this. See the code below which generates the output 2.37 as expected.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
string floatString = "2.37";
istringstream floatStringStream(floatString);
float f;
floatStringStream >> f;
cout << f;
return 0;
}
Run the following command with gcc for instance (or something similar if you have a different scenario):
Command: g++ main.cpp && ./a.out
Output: 2.37

Related

Is there any way to convert string characters into integer? [duplicate]

I am trying to take a string and parse it into an int. I have read the many answers out there, and it seems that using stoi is the most up-to-date way. It appears to me that stoi uses std, but I am getting Function 'stoi' could not be resolved despitre using namespace std;
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include<stdlib.h>
using namespace std;
int main(int argc, char* argv[]) {
string line = "";
string five = "5";
int number = stoi(five); //Error here with stoi
return 0;
}
Any ideas what is causing this?
Update:
I am using Eclipse. My flags are: -c -fmessage-length=0 -std=c++11
If you are using GCC or MINGW, then this is the answer:
std::stoi doesn't exist in g++ 4.6.1 on MinGW
This is a result of a non-standard declaration of vswprintf on
Windows. The GNU Standard Library defines
_GLIBCXX_HAVE_BROKEN_VSWPRINTF on this platform, which in turn disables the conversion functions you're attempting to use. You can
read more about this issue and macro here:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37522.
If you're willing to modify the header files distributed with MinGW,
you may be able to work around this by removing the
!defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF) macro on line 2754 of
.../lib/gcc/mingw32/4.6.1/include/c++/bits/basic_string.h, and adding
it back around lines 2905 to 2965 (the lines that reference
std::vswprintf). You won't be able to use the std::to_wstring
functions, but many of the other conversion functions should be
available.
Please always provide platform and compiler information.
Toggle on C++11 support in your compiler flags. -std=c++11 for a recent gcc. For Eclipse, please refer to the corresponding question in the FAQ and this answer explains how to get rid of the remaining Eclipse warning.
If you are amenable to parsing an int another way, how about using an STL algorithm and a C++11 lambda expression?
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "12345";
int num = 0;
for_each(str.begin(), str.end(), [&num](char c){ num = 10 * num + (c - '0'); });
cout << str << " = " << num << endl;
}

Strange Number Conversion C++

So I have the following code:
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main()
{
array<long, 3> test_vars = { 121, 319225, 15241383936 };
for (long test_var : test_vars) {
cout << test_var << endl;
}
}
In Visual Studio I get this output:
121
319225
-1938485248
The same code executed on the website cpp.sh gave the following output:
121
319225
15241383936
I expect the output to be like the one from cpp.sh. I don't understand the output from Visual Studio. It's probably something simple; but I'd appreciate it nonetheless if someone could tell me what's wrong. It's has become a real source of annoyance to me.
The MSVC uses a 4Byte long. The C++ standard only guarantees long to be at least as large as int. Therefore the max number representable by a signed long is 2.147.483.647. What you input is too large to hold by the long and you will have to use a larger datatype with at least 64bit.
The other compiler used a 64bit wide long which is the reason why it worked there.
You could use int64_t which is defined in cstdint header. Which would guarantee the 64bit size of the signed int.
Your program would read:
#include <cstdint>
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int64_t, 3> test_vars = { 121, 319225, 15241383936 };
for (int64_t test_var : test_vars) {
cout << test_var << endl;
}
}

How to print hex from uint32_t?

The code I have been working on requires that I print a variable of type uint32_t in hexadecimal, with a padding of 0s and minimum length 8. The code I have been using to do this so far is:
printf("%08lx\n",read_word(address));
Where read_word returns type uint32_t. I have used jx, llx, etc. formats to no avail, is there a correct format that can be used?
EDIT:
I have found the problem lies in what I am passing. The function read_word is returns a value from a uint32_t vector. It seems that this is the problem that is causing problems with out putting hex. Is this a passing by reference/value issue and what is the fix?
read_word function:
uint32_t memory::read_word (uint32_t address) {
if(address>(maxWord)){
return 0;
}
return mem[address];
}
mem deceleration:
std::vector<uint32_t> mem=decltype(mem)(1024,0);
To do this in C++ you need to abuse both the fill and the width manipulators:
#include <iostream>
#include <iomanip>
#include <cstdint>
int main()
{
uint32_t myInt = 123456;
std::cout << std::setfill('0') << std::setw(8) << std::hex << myInt << '\n';
}
Output
0001e240
For C it gets a little more obtuse. You use inttypes.h
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
uint32_t myInt = 123456;
printf("%08" PRIx32 "\n", myInt);
return 0;
}
Output
0001e240
Note that in C, the constants from inttypes.h are used with the language string-concatenation feature to form the required format specifier. You only provide the zero-fill and minimum length as a preamble.
%jx + typecast
I think this is correct:
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint32_t i = 0x123456;
printf("%08jx\n", (uintmax_t)i);
return 0;
}
compile and run:
gcc -Wall -Wextra -pedantic -std=c99 main.c
./a.out
Output:
00123456
Let me know if you can produce a failing test case.
Tested in Ubuntu 16.04, GCC 6.4.0.

C++ _byteswap_ulong was not declared in this scope

when I try to compile my program I get this error:
error: ‘_byteswap_ushort’ was not declared in this scope
long lNum = (long)_byteswap_ushort(iNum);
this is the program:
#include <iostream>
#include <sstream>
#include <stdlib.h>
using namespace std;
int main()
{
long inputNum;
cout << "Input number:\n";
cin >> inputNum;
long Num = (long)_byteswap_ulong(iNum);
stringstream oss;
oss << hex << Num;
string mystring = oss.str();
return 0;
}
I thought that including stdlib should solve the problem. Is there any other library I should include?
The program is compiled with:
g++ -m32 -o output32 prog.cpp
You seem to be trying to use a function specific to MS Visual C++ compiler, which is not available in GCC. Use an appropriate GCC builtin instead.
Seems like uint32_t __builtin_bswap32(uint32_t x) would be appropriate in this case.
Another option, if you wanted a portable solution, would be to use something like Boost Endian library.

Read string math-formula into cpp as double from external input-file

I am relatively new to c++ coding and try to write a program to solve differential equations numerically. I use codeBlocks as the compiler for that and work under windows. The numeric solver already works well.
My program contains of some very long formulas which are created by mathematica and converted into cpp-language. Then the formulas are stored in a .txt-file.I can already read the formula as a string, but not use it to calculate things because the program has to interpret the formula as a double-type math and not as a string. The problem here is, that my formula does not contain only numbers, but letters as variables (their value is set in the program) and other mathematical symbols. That is why I think I cannot just use "atof" (http://www.cplusplus.com/reference/cstdlib/atof/?kw=atof) or other conversion functions. (If I am wrong at this point, I would be glad to learn how to use the function for this problem!)
Here is some example code from my little program:
//Program to solve ODEs
#include <iostream>
#include <math.h>
#include <cmath>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <time.h> //to measure the time
#include <stdio.h>
#include <conio.h>
using namespace std;
int main(void)
{
double k1=0;
ifstream file("Formelvu1.txt");//file with the fromula
string line;
stringstream longform;
while(getline(file, line)){ //read the formula and store them
longform << line; //store the string in "longform"
cout << longform;
}
return 0;
for(double t=0; t<10; t++){
k1 = (longform) * t; //simple operation with the formula
}
return 0;
}
This code doesn't work, becuase longform is no double...
longform is a string with something like: ab+pow(t,3)-sin(tb)/x.
I already found several questions related to this topic, but none of them was easy enough for me to understand or the right thing I want to do:
How can I convert string to double in C++?
From what I understand is this guy trying the nearest from what I wish to do:
Evaluate math formula from String using ScriptEngine
But I don't understand the code completely.
If it is useful for my problem: What does this part do?
try{
return (Double)engine.eval(tmp);
}
catch(Exception fexp)
{
}
I also heard about parser which can interpret the xpressions line muparser:
http://muparser.beltoforion.de/mup_eval.html
But I don't know if this would be more than I need...
I appreciate every answer/response and help with this problem.
Thank you!
You have to study carefully what is included in the basic C/C++ language and standard library and what not.
However, if you get a C++ compatible expression from mathematica, then you can let the C++ compiler do its work as in
double myfunc(double a, double b, double c, double t, double x) {
return
#include "Formelvu1.txt"
;
}