Classes and Objects

  • + 0 comments

    Mine wors in my compiler, but when I put the exact same code in the Hackerank compiler, it gives me the wrong answer. Very bizarre:

    class Student
    {
        std::vector<int> scores{};
    
    public:
        void input()
        {
            // If std::cin buffer has '\n', then clear the buffer
            if (std::cin.peek() == '\n') {
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
    
            std::string str;
    
            //read input and store it in a string "str", note that this includes the newline character '\n';
            std::getline(std::cin, str); //a way to remove the newline from the string
    
            std::stringstream iss( str );
    
            //convert the numbers on the string to an integers and store it as elements of vector str_int
            int score;
            while (iss >> score)
            {
                scores.emplace_back(score);
            }
        }
    
        int calculateTotalScore()
        {
            int total{0};
            for (const auto &num: scores)
            {
                total += num;
            }
            return total;
        }
    };