Use return value of function call within main in c++?

Viewed 52

I am quite new to programming, so I suppose there could be a straight forward solution to my problem. (The exercise is about function overload in c++). I want my main function to use the output of a function and print it in a table. The user either inputs an atomic element (as a string), so the output of the lookup()-function should be the respective atomic number, or the user enters the atomic number to get the atomic element (string) as an output. However, I get the following error message when trying to compile:

error: 'output' was not declared in this scope if(output == "error" || output == 1){

What is my mistake here?

// use functions from the standard library (like cout)
#include <iostream>
#include <cctype>
#include <string>
#include <iomanip>

// to avoid name-clashes, create a namespace
namespace exercises
{
  // add elements + lookup functionality
  int lookup(std::string name);
  std::string lookup(int atomicNumber);
  
} /* end of namespace exercises */

// I want to use the functions from our new namespace...
using namespace exercises;

//arrays
std::string t[4] = {"H", "Rh", "Cl", "C"};
int s[4] = {1, 45, 17, 6};

//global variables
//auto input;
//auto output;
//std::string output;

int main(void)
{
//declare input variable as string temporarily 
std::string input;

//lookup something
std::cout << "Enter element or atomic number to look up:" << std::endl;
std::cin >> input;

//if input is atomic number, make it of type integer to match function input type
if(std::isdigit(input[0])){
  std::stoi(input);
};

auto output = lookup(input);


if(output == "error" || output == 1){
  std::cout << "Invalid input!" << std::endl;
};

//print output
std::cout << "|**Sample Input**|**Sample Output**|" << std::endl;
std::cout << "|" << std::setfill('-') << std::setw(16) << "|" << std::setfill('-') << std::setw(16) << "|" << std::endl;
std::cout << "|" << std::left << std::setw(16) << input << "|" << std::left << std::setw(16) << output << "|" << std::endl;

return 0;
}

//function definition element symbol --> atomic number
int lookup(std::string input){
  //check if input is valid, ie if exists in array t
  for(unsigned int i=0; i<sizeof(t); i++){
    if(input == t[i]){
      int output; 
      output = s[i];
      
  return output;
    };
  };
  int output = 1;
  return output;
}
  
//function definition atomic number --> element symbol
std::string lookup(int input){
  //check if input is valid, ie if exists in array s
  for(unsigned int i=0; i<sizeof(s); i++){
    if(input == s[i]){
      std::string output;
      output = t[i];
      
  return output;
    };
  };
  std::string output = "error";
  return output;
}
 
0 Answers
Related