How to only store specific characters of the user's input?

Viewed 59

I want to store the value of specific characters from the user input? like for example:

#include <iostream>
#include <string>

int main(){
int useryear;
std::cout << "\n\tType your favourite year:\n";
std::cout << "\t >> ";
std::cin.ignore(0);
getline(std::cin, useryear);

return 0;
}

So, for example the user entered 1933 How to store only the 19?? or the first two characters they typed?

I think to store the 33 i have to change "cin.ignore(0);" to "cin.ignore(2);"

1 Answers

Personally I would opt for Remy's suggestion (from the comments) if given the choice.

That being said, you could limit the number of characters you read using one of the get overloads of istream.

#include <string>
#include <iostream>
#include <limits>

int main()
{
    std::string buffer(3, '\0');
    if (std::cin.get(buffer.data(), 3))
    {
        try
        {
            const int year{std::stoi(buffer)};
            std::cout << "Year: " << year << '\n';
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        catch(const std::invalid_argument& ex)
        {
            std::cerr << "Invalid input" << '\n';
        } 
    }
}
Related