I am trying to convert string value into its hex form, but not able to do.
Following is the C++ code snippet, with which I am trying to do.
#include <stdio.h>
#include <sys/types.h>
#include <string>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
using namespace std;
int main()
{
string hexstr;
hexstr = "000005F5E101";
uint64_t Value;
sscanf(hexstr.c_str(), "%" PRIu64 "", &Value);
printf("value = %" PRIu64 " \n", Value);
return 0;
}
The Output is only 5, which is not correct.
Any help would be highly appreciated.
Thanks,
Yuvi
If you're writing C++, why would you even consider using sscanf and printf? Avoid the pain and just use a stringstream:
int main() {
std::istringstream buffer("000005F5E101");
unsigned long long value;
buffer >> std::hex >> value;
std::cout << std::hex << value;
return 0;
}
#include <sstream>
#include <string>
using namespace std;
int main(){
string myString = "45";
istringstream buffer(myString);
uint64_t value;
buffer >> std::hex >> value;
return 0;
}
Related
I have a csv file in Excel that has a column of double data. I am trying to read that column and store the values in a vector variable using a while loop. I tried to use getline and then convert them into a double using stod.
The column has more values, but this is how the csv file looks like:
A
B
51.32
53.62
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream myFile("CData.csv");
int i= 0;
string val;
std::vector<double> y;
while (getline(myFile, val, ',')) {
y.push_back(stod(val));
cout << "test: " << y.at(i);
i++;
}
return 0;
}
I'm not sure what I'm doing wrong. Somehow, there is no output on the console app. I tried it with string ang it worked but when I try to convert to a double, it doesn't. Is there another way to do this, or did I miss something in the code? Thanks, I'm new to coding.
You need to first parse the line and then look at the line for comma separated data. Also you need to chek if data is digits or not.
Here is an example:
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
ifstream myFile("CData.csv", std::ios::in);
int i= 0;
string val;
std::string line;
std::vector<double> y;
while (getline(myFile, line))
{
std::stringstream sstr(line);
while (getline(sstr, val, ','))
{
bool flag = true;
for (auto c : val)
if (!isdigit(c))
flag = false;
if (flag){
y.push_back( std::stod(val));
std::cout << "number: " << y.at(i) << std::endl;
i++;
}
else std::cout << "not number: " << val << std::endl;
}
}
return 0;
}
Good luck!
I have a code which will convert the float value to string, i have written like below
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
float myFloat= 10.80;
std::ostringstream ss;
ss << myFloat;
cout<<"value = " << ss.str();
std::string s(ss.str());
cout<<"value = " << s;
return 0;
}
But the problem is when my value is 10.66 its coming 10.66 but when its 10.80 its coming like 10.8 or when its 10.00 its coming 10 only .
How can i print the complete value
Try this code .
Use the setprecision function with '2' .
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
float myFloat= 10.80;
stringstream stream;
stream << fixed << setprecision(2) << myFloat;
string s = stream.str();
cout<<"value = " << s;
return 0;
}
The trailing zeros are only kept if you set either fixed or scientific mode.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x = 4.2;
cout << fixed << setprecision(2);
cout << x << endl;
return 0;
}
It seems you want something like below.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
int main() {
float myFloat= 10.80;
std::ostringstream ss;
ss << fixed << setprecision(2) << myFloat;
cout<<"value = " << ss.str();
std::string s(ss.str());
cout<<"value = " << s;
}
Probably the least complicated way would be to use printf instead of std::cout. There you can specifically specify how many digits are to be displayed.
#include "stdio.h"
printf("%3.2f",myfloat);
where 3 is the # of digits before and 2 the # of digits after the dot, either can be left out. Append '\n' to the string if you want a new line.
EDIT: Ok, I did not know about setprecision(2).
I want to assign integer to a char pointer using stringstream. But I am getting error while running this program at line ss >> p. Please help me here i want integer to go into the buffer first and the it must be assigned to a char*.
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char *p;
ss << n;
ss >> p; //not working
cout << ss;
return 0;
}
Use stringstream::str to get a C++ string, then use .c_str() on the string:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n = 100;
char* p;
ss << n;
string tmp = ss.str();
p = const_cast<char*>(tmp.c_str());
cout << "p: " << p << '\n';
return 0;
}
Beware that the char pointer becomes invalid as soon as the string goes out of scope. If you need some kind of factory function behavior, return a string by value, use strlcpy or maybe new and shared_ptr.
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char buffer[100];
char *p = buffer;
ss << n;
ss >> p;
cout << p;
return 0;
}
This is fixing only the problem you directly encountered - there's no storage behind p so it will crash. Stylistically there are many other things to improve / fix, but this should show you what part of this was actually wrong.
I have the following:
char const* code = "3D";
I need to convert this 2-digit lexical hex into a std::string, which will be a string with length of 1 (not including null terminator). I have the boost library at my disposal as well. How can I do this?
In the example above, I should have a std::string that prints "=" if properly converted.
I think something on this order should work:
std::istringstream buffer("3D");
int x;
buffer >> std::hex >> x;
std::string result(1, (char)x);
std::cout << result; // should print "="
For example, using only standard C++03:
#include <cstdlib>
#include <string>
#include <iostream>
int main() {
char const* code = "3D";
std::string str(1, static_cast<char>(std::strtoul(code, 0, 16)));
std::cout << str << std::endl;
}
In a real application, you'd have to test whether the entire string has been converted (second argument to strtoul) and whether the conversion result is in the allowed range.
Here is a more elaborate example, using C++11 and Boost:
#include <string>
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <boost/numeric/conversion/cast.hpp>
template<typename T>
T parse_int(const std::string& str, int base) {
std::size_t index = 0;
unsigned long result = std::stoul(str, &index, base);
if (index != str.length()) throw std::invalid_argument("Invalid argument");
return boost::numeric_cast<T>(result);
}
int main() {
char const* code = "3D";
std::string str(1, parse_int<char>(code, 16));
std::cout << str << std::endl;
}
In Boost release 1.50 (coming this May), you would simply write
string s;
boost::algorithm::unhex ( code, std::back_inserter (s));
Works on std::string, std::wstring, QtString, CString, etc, etc.
It's not C++ but you can still use the good old scanf:
int d;
scanf("%x", &d);
Or from a string using sscanf:
int d;
sscanf(code, "%x", &d);
And using a std::string:
int d;
sscanf(code.c_str(), "%x", &d);
For some case the C format function (scanf & printf families) are easier to use than the object-oriented equivalent.
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.