I'm having trouble converting a string into a double.
My string has been declared using the "string" function, so my string is:
string marks = "";
Now to convert it to a double I found somewhere on the internet to use word.c_str(), and so I did. I called it and used it like this:
doubleMARK = strtod( marks.c_str() );
This is similar to the example I found on the web:
n1=strtod( t1.c_str() );
Apparently, that's how it's done. But of course, it doesn't work. I need another parameter. A pointer I believe? But I'm lost at this point as to what I'm suppose to do. Does it need a place to store the value or something? or what?
I also need to convert this string into a integer which I have not begun researching as to how to do, but once I find out and if I have errors, I will edit this out and post them here.
Was there a reason you're not using std::stod and std::stoi? They are at least 9 levels more powerful than flimsy strtod.
Example
#include <iostream>
#include <string>
int main() {
using namespace std;
string s = "-1";
double d = stod(s);
int i = stoi(s);
cout << s << " " << d << " " << i << endl;
}
Output
-1 -1 -1
If you must use strtod, then just pass NULL as the second parameter. According to cplusplus.com:
If [the second parameter] is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
And it's not required to be non-NULL.
Back in the Bad Old Dark Days of C, I'd do something ugly and unsafe like this:
char sfloat[] = "1.0";
float x;
sscanf (sfloat, "%lf", &x);
In C++, you might instead do something like this:
// REFERENCE: http://www.codeguru.com/forum/showthread.php?t=231054
include <string>
#include <sstream>
#include <iostream>
template <class T>
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int main()
{
int i;
float f;
// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string<int>(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
if(from_string<float>(f, std::string("123.456"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}
Personally, though, I'd recommend this:
http://bytes.com/topic/c/answers/137731-convert-string-float
There are two ways. C gives you strtod which converts between a char
array and double:
// C-ish:
input2 = strtod(input.c_str(), NULL);
The C++ streams provide nice conversions to and from a variety of
types. The way to use strings with streams is to use a stringstream:
// C++ streams:
double input2;
istringstream in(input);
input >> input2;
We can define a stringTo() function,
#include <string>
#include <sstream>
template <typename T>
T stringTo(const std::string& s) {
T x;
std::istringstream in(s);
in >> x;
return x;
}
Then, use it like
std::cout << stringTo<double>("-3.1e3") << " " << stringTo<int>("4");
Related
I have been trying to make a Convert.To command like in C# in C++ but I dont want to do it like "IntToString" Instead I want to make it like "ToString" just like in C#. I was wondering how can I know the format of the parameter given inside the function? Or is there any other way to do this?
#include <iostream>
#include <sstream>
class converting {
public:
std::string Int32ToString(int x) {
std::stringstream asd;
asd << x;
std::string cnvrtd;
asd >> cnvrtd;
return cnvrtd;
}
int StringToInt32(std::string x) {
std::stringstream asdf(x);
int cnvrtd;
asdf >> cnvrtd;
return cnvrtd;
}
};
int main() {
converting Convert;
std::cout << "This is for a test. Avaiable options are:" << std::endl << "StringToInt32" << std::endl << "Int32ToString" << std::endl;
std::string firstinput;
std::cin >> firstinput;
if (firstinput == "StringToInt32") {
std::string input;
int result;
std::cin >> input;
result = Convert.StringToInt32(input);
std::cout << result;
return 0;
}
else if (firstinput == "Int32ToString") {
int input;
std::string result;
std::cin >> input;
result = Convert.Int32ToString(input);
std::cout << result;
return 0;
}
else {
std::cout << "Please enter a valid input";
return 0;
}
}
When you say - Format of the parameter given inside the function, do you mean, how do you know the data type of the parameter. If that's the case, you will have to write functions for all the data types for which you want to support conversion, inside your Converting class with same function name, this is called function overloading in C++. e.g.
std::string convert (int n){}
std::string convert (float n){}
std::string convert (double n){}
When you will invoke this convert function compiler will choose appropriate overloaded function according to the data type.
However there is smaller way to achieve the same functionality by writing a template function like
template<class Dt>
std::string Convert (Dt n){
return std::to_string(n);
}
Hope I am not missing considering any limitations if you have mentioned.
So I have been trying for 1.30 hour to get this to work. I am new indeed, but I have searched all over the place and couldn't find an exact answer. I do not wish to do this another way, as it would take away the entire purpose of learning to code. I have to find why this thing isn't working. I tried dozens if not hunderds of syntaxes, but nothing works.
I want to read in a const char* name, than count the number of elements in it, so I thought had to be strlen(), and than output the name and the number of elements. If that works I can write the rest of the code.
#include <iostream>
using namespace std;
int main()
{
//writing your name, and counting the characters including \0
int a;
const char* name;
a = int strlen(name);
cin.getline(name);
cout << name;
cout >> a;
return 0;
}
There are a lot of problems with your code.
You are not allocating any memory for cin.getline() to read into. const char* name; is declaring an uninitialized pointer to nothing. You have to allocate memory for name before you can then read any data into it.
cin.getline() expects two input parameters (a pointer to an allocated buffer, and the max number of characters the buffer can hold), but you are only passing in one value.
You are calling strlen() before you have read anything into name (and there is a syntax error on your strlen() statement anyway).
You are passing a to std::cout using >>, but std::ostream does not implement the >> operator. You have to use << instead.
And lastly, don't use using namespace std;.
Try this instead:
#include <iostream>
#include <cstring>
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
std::cin.getline(name, 32);
a = std::strlen(name);
std::cout << "You entered: " << name << std::endl;
std::cout << "It is << a << " chars in length" << std::endl;
return 0;
}
Or, if you really don't like using std:: everywhere, at least use using <identifier>; instead of using namespace std;:
#include <iostream>
#include <cstring>
using std::cin;
using std::strlen;
using std::cout;
using std::endl;
int main()
{
//writing your name, and counting the characters including \0
int a;
char name[32];
cin.getline(name, 32);
a = strlen(name);
cout << "You entered: " << name << endl;
cout << "It is " << a << " chars in length" << endl;
return 0;
}
Now, that being said, the preferred solution is to use std::getline() instead of cin.getline():
#include <iostream>
#include <string>
int main()
{
int a;
std::string name;
std::getline(std::cin, name);
a = name.length();
std::cout << "You entered: " << name << std::endl;
std::cout << "It is " << a << " chars in length" << std::endl;
return 0;
}
I found a working solution, although I don't see where I had gone wrong. But this does exactly what I want using const char* and strlen() without using std::string.
Thanks for all your help, you have all pointed me to the correct direction.
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main ()
{
const char *name;
int len;
name = "stephane";
len = strlen(name);
cout << name;
cout << len;
return(0);
}
As another user has pointed out, I think it's a good idea for you to take a few steps back and read the basics until you understand how pointers work.
A const char* is that: const. It could be used usually while doing things like this:
const char* cpName = "Stephane"; //expected not to change through the program's lifetime
char* pName = "Stephane"; //can be changed to point to something else
char *pOther = "Vada";
pName = pOther; //pName now points to the string "Vada"
cpName = pOther; //this won't compile as cpName is const
Before converting wstring to double - how to validate it with regex? Java no problem, but C++ raising questions.. :)
I suppose you have a string and you want to know if it is a double or not. The following code does not use regular expressions. Instead it initializes a stringstream and reads a double from it. If the string starts with something non-numeric, then ss.fail() will be set. If it starts with a number, but does not read the whole string, then there's something non-numeric at the end of the string. So if everything went well and the string is really only a number, then ss.eof() && !ss.fail() will be true.
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss("123.456");
double mydouble;
ss >> mydouble;
if (ss.eof() && !ss.fail())
std::cout << "yay, success: " << mydouble << std::endl;
else
std::cout << "that was not a double." << std::endl;
return 0;
}
There's also std::wstringstream if you need to convert wide character strings.
You might also want to have a look at the boost libraries, especially at Boost.Lexical_Cast.
With this library you could do the following:
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
try
{
double mydouble = boost::lexical_cast<double>("123.456");
std::cout << "yay, success: " << mydouble << std::endl;
}
catch(const boost::bad_lexical_cast &)
{
std::cout << "that was not a double." << std::endl;
}
return 0;
}
Or maybe it is simpler to do that this way:
std::wstring strKeyValue = "147.sd44";
double value = (double) _wtof(strKeyValue.c_str());
And if strKeyValue==0 then it means it's not double.
I have a string: (66)
Then I convert it to double and do some math: atof(t.c_str()) / 30
then I convert it back to string: string s = boost::lexical_cast<string>(hizdegerd)
Problem is when I show it on label it becomes 2,20000001.
I've tried everything. sprintf etc.
I want to show only one digit after point.
hizdegerd = atof(t.c_str()) / 30;
char buffer [50];
hizdegerd=sprintf (buffer, "%2.2f",hizdegerd);
if(oncekideger != hizdegerd)
{
txtOyunHiz->SetValue(hizdegerd);
oncekideger = hizdegerd;
}
I think I'd wrap the formatting up into a function template, something like this:
#include <iostream>
#include <sstream>
#include <iomanip>
template <class T>
std::string fmt(T in, int width = 0, int prec = 0) {
std::ostringstream s;
s << std::setw(width) << std::setprecision(prec) << in;
return s.str();
}
int main(){
std::string s = fmt(66.0 / 30.0, 2, 2);
std::cout << s << "\n";
}
You can use this way of conversion back to string and then only the wished number of digits for the precision will be taken in consideration:
ostringstream a;
a.precision(x); // the number of precision digits will be x-1
double b = 1.45612356;
a << b;
std::string s = a.str();
Since you wrote "I want to show":
#include<iostream>
#include<iomanip>
int main()
{
std::cout << std::fixed << std::setprecision(1) << 34.2356457;
}
Output:
34.2
By the way, sprintf is buffer-overflow-vulnerable and is not C++ .
I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.