I have a variable, value, declared in a class, input. I want to use it inside main. Here is my code.
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <filesystem>
#include <string>
class input {
public :
int add() {
std::string Type;
std::ifstream typeFile("type.txt");
if (!typeFile.is_open()) {
std::cerr << "Error opening variable type file." << std::endl;
return 1;
}
std::getline(typeFile, Type);
typeFile.close();
std::string Data;
std::ifstream dataFile("data.txt");
if (!dataFile.is_open()) {
std::cerr << "Error opening variable data file." << std::endl;
return 1;
}
std::getline(dataFile, Data);
dataFile.close();
if (Type == "int") {
int value = std::stoi(Data);
} else if (Type == "bool") {
bool value = std::stoi(Data);
} else if (Type == "string") {
std::string value = Data;
} else {
std::cerr << "Unknown type." << std::endl;
return 1;
}
}
};
int main() {
input hello;
hello.add();
}
I tried making the variable value public but I got an error message. I do not want to move the code in input to main, I just want it to be so I can use value in main. What I want is something where I can do
int main() {
input hello;
hello.add();
std::cout << value;
}
valuevariable, you have 3 completely unrelated ones (and only one of them lives near the end ofadd()). Sure, there are ways in which you can return "this-or-that", but all of them are quite above your current level.input? Are you trying to read configuration of your program? If config is desired why not use some commonly used solution with YAML/JSon/XML/ini?