-1

so i made a very simple stack that works just fine and decided to turn it to template, it also worked fine, but when i turned it to integer something happened with the input

string m;
    getline(cin, m);
    linkedliststack<int> str;
    for (int i = 0; i < m.length(); i++)
    {
        str.push(m[i]);
    }

It appeared that by using this input method the m[i] becomes char turned to int, in other words turned to ASCII code, so if i enter 1 it give 48, 2 give 49 etc. The simple solution is of course this.

str.push(m[i]-48)

But is there a way to make it automated, e.i. with if condition or anything? If yes then what is the required syntax?

Thanks.

AHAMES
  • 61
  • 11

3 Answers3

0

Strings push_back is

void push_back (char c);

i.e. it takes a char. If you want the value as a char you have to convert it by using e.g. itoa or the like.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

I must apologize for repeating this question as it is related to this on How do I get the type of a variable? sorry this is my first time to ask a question.

So to solve this i made a new function in the class

string type(){ return  typeid(head->value).name(); } 

and the new condition solves the problem.

if (str.type()== "int")
Community
  • 1
  • 1
AHAMES
  • 61
  • 11
0

There may be an enable_if solution out there if you're able to use C++14. Maybe even an SFINAE solution. However I'm not very experienced with that.

I'm assuming your push method is declared as

void push(typename T);

Then what you are doing is implicitly converting a char (m[i]) to an int str.push(m[i]);

You could provide an overloaded template method that can handle a char Input and convert it correctly to your typename.

Something like this:

void push(const char input)
{
    push(atoi(input));
    // push(input-48);
}

A lot of errors may have to be considered though: What happens if atoi() cannot convert the char to an integer? In your case of -48 you will push unintended numbers on the Stack if input is a nonnumber char. What will happen if the template is not instantiated with .

Tomas Dittmann
  • 424
  • 7
  • 18