std::string out of range eventhough I am not using any index

Refresh

5 days ago

Views

21 time

-1

I get the following error message: string subscript out of range. I believe it has more to do with my templates definition because I am not using any string subscripts anywhere. I have not been able to figure this out, I have tried defining and implementing my templates in various ways but the result is the same.

//in ival.hpp
#ifndef IVAL_HPP
#define IVAL_HPP

#include<iostream>
#include<string>
#include<sstream>

template <typename T> bool is_type(std::string);

template<> bool is_type<int>(std::string);

template<typename T> T get_type(std::string);

bool yesNo(std::string);

#include "ival.tpp"

#endif /*IVAL_HPP*/

Then my template functions implementation:

//in ival.tpp
#include "ival.hpp"
#ifndef IVAL_IMP_HPP
#define IVAL_IMP_HPP

template <typename T> bool is_type(std::string input)
{
    T test;
    std::stringstream ss(input);
    if (ss >> test)
    {
        std::string remainder;
        ss >> remainder;
        return (remainder.size() == 0);
    }
    else return false;
}

template<typename T> T get_type(std::string prompt)
{
    T output;
    std::cout << prompt + " ";
    std::string Input;
    while (std::getline(std::cin, Input) && !is_type<T>(Input))
        std::cout << "Invalid input type. Please try again.\n" << prompt + " ";
    std::stringstream(Input) >> output;
    return output;
}

#endif /*IVAL_HPP*/

bool and fully specialized template definitions:

//in ival.cpp
#include "ival.hpp"

template<> bool is_type<int>(std::string input)
{
    if (is_type<double>(input))
    {
        int test;
        std::string remainder;
        std::stringstream(input) >> test >> remainder;
        while (remainder[remainder.size() - 1] == '0') remainder.pop_back();
        remainder.pop_back();
        return (remainder.size() == 0);
    }
    else return false;
}

bool yesNo(std::string prompt)
{
    while (true)
    {
        char output{ get_type<char>(prompt + " [y/n]:") };
        if (output == 'y' || output == 'Y' || output == 'n' || output == 'N') return (output == 'y' || output == 'Y');
        std::cout << "Invalid input. Please try again.\n";
    }
}

And my main, where the function get_digit() is causing problems. I only want to accept a single digit, that is why I get_type<char>, and then check if it is_type<int>(string).

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<vector>
#include "ival.hpp"

char get_digit()
{
    while (true)
    {
        char output{ get_type<char>("What year do you want to extract? (Only enter a single digit 1-9):") };
        std::string test(1, output);
        std::cout << test << std::endl;
        if (is_type<int>(test)) return output;
        std::cout << "Invalid input. Please try again.\n";
    }
}

int main(void)
{
    char year{ get_digit() };
return 0;
}

0 answers