'Convert numeric struct to textual line of numbers on C++
Need some idea how to convert struct (might be also nested) to line of strings where each string is the number of the struct according to the order. I hope i clear enough. For example:
struct MyStruct
{
int a;
float b;
};
struct External
{
double c;
MyStruct d;
};
void main()
{
External x;
x.c = 2.345;
x.d.a = 12;
x.d.b = 3.8f;
std:string res = convert_to_string (&x);
cout << res;
// Expected print result:
// "2.345, 12, 3.8"
}
The struct can be very long, so the solution of sorts of itoa(dtoa) or sprintf for each field is possible, but very long and needs code update for every struct change. Probably some kind of struct run-time or precompile parsing and serialization is needed here.
Ideas ?
Solution 1:[1]
What about this? C++ to the rescue :)
#include <iostream>
struct MyStruct {
int a;
float b;
friend std::ostream& operator<<(std::ostream& os, const MyStruct& ms) {
std::cout << std::to_string(ms.a) << " " << std::to_string(ms.b);
return os;
}
};
struct External {
double c;
MyStruct d;
friend std::ostream& operator<<(std::ostream& os, const External& e) {
std::cout << std::to_string(e.c) << " " << e.d;
return os;
}
};
int main() {
External x;
x.c = 2.345;
x.d.a = 12;
x.d.b = 3.8f;
std::cout << x << std::endl;
// Expected print result:
// "2.345, 12, 3.8"
}
Or if you really want a string:
#include <iostream>
struct MyStruct {
int a;
float b;
std::string to_string() const {
std::string str = std::to_string(this->a);
str += " ";
str += std::to_string(this->b);
return str;
}
};
struct External {
double c;
MyStruct d;
std::string to_string() const {
std::string str = std::to_string(this->c);
str += " ";
str += this->d.to_string();
return str;
}
};
int main() {
External x;
x.c = 2.345;
x.d.a = 12;
x.d.b = 3.8f;
std::cout << x.to_string() << std::endl;
// Expected print result:
// "2.345, 12, 3.8"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcell Juhász |
