Greetings from sunny London. I know some C, have written in Lazarus Pascal, enjoy coding for pleasure, and decided to dabble in C++. Lots of terminology still escapes me.
I was experimenting with structures and unions and quickly realised that unions do not handle strings well and according to web searches, I should consider using “#include <variant>” and “std::variant<int, std::string> var; var = "hello";”
But the latter line produces a series of errors which seem to cluster around “C2039 ‘variant’: is not a member of ‘std’”
and
“C2065 ‘variant’: undeclared identifier”
un-commenting using namespace std; does not improve the situation.
Any help appreciated
Stephanos
Code:// StructuresV2-2.cpp // OS - Windows 10 Enterprise // Compiler - C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\bin\Hostx64\x64>cl.exe // Microsoft(R) C / C++ Optimizing Compiler Version 19.26.28806 for x64 // Copyright(C) Microsoft Corporation.All rights reserved. // usage: cl[option...] filename...[/ link linkoption...] // C : \Program Files(x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.26.28801\bin\Hostx64\x64 > // Application - MS Visual Studio Community 201916.6.3 // Experiement to see if a union can be a field in a structure // It can. But unions limited ability to store/use string. // Use: // #include <variant> // std::variant // to replace union using namespace std; #include <iostream> #include <variant> #include <string> // needed to use std::to_string() struct coffeeBean { std::string name; std::string country; int strength; union internationalgrade; } newBean; // int main() { newBean.name = "Flora"; newBean.country = "Mexico"; newBean.strength = 9; std::cout << "Bean: " + newBean.name + " From: " + newBean.country; std::cout << " Strength: " + std::to_string(newBean.strength) << std::endl; std::variant<int, std::string> var; var = "hello"; return 0; }