KripC2160
KripC2160

Reputation: 49

How do you allow comma to be used for user input for integer based input c++?

I am pretty new to c++ and I am trying to make a program that prints out the number based on user input. But when you add a , it breaks the code since it is not part of integers. What should I do?

I made a simplified code because I want to do more with the integers:

#include <iostream>
using namespace std; 

int main(){
    int player_input;
    cout << "Insert the number" << endl;
    cin >> player_input;
    cout << player_input;
    return 0; //the code doesn't work if you add a comma in cin when you run such as "3,500"
}

Upvotes: 2

Views: 750

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490663

I think @Jarod42 is on the right general track, but I don't think there's usually a good reason to define your own locale for this task. In most cases you're doing to have a pre-defined locale you can use to do the job. For example, this code:

#include <locale>
#include <iostream>

int main() {
    std::cin.imbue(std::locale("en-US"));

    int i;
    std::cin >> i;

    std::cout << i << "\n";
}

...let's me enter a number like 3,400, and it'll print it back out as 3400, to show that it read all of that as a single number.

In a typical case, you'd probably want to simplify things even a bit further by using a nameless locale (std::cin.imbue(std::locale(""));, as this will normally at least try to use a locale matching the what the operating system is configured for, so it would support an American entering 3,400, and (for example) a German entering 3.400 instead.

Upvotes: 1

Jarod42
Jarod42

Reputation: 218268

With <locale>, you might do:

#include <locale>

template<typename T> class ThousandsSeparator : public std::numpunct<T> {
public:
    ThousandsSeparator(T Separator) : m_Separator(Separator) {}

protected:
    T do_thousands_sep() const override { return m_Separator; }

    std::string do_grouping() const override { return "\03"; }

private:
    T m_Separator;
};

int main() {
    ThousandsSeparator<char> facet(',');
    std::cin.imbue(std::locale(std::cin.getloc(), &facet));
    int n;
    std::cin >> n;
    // ...
}

Demo

Upvotes: 1

cigien
cigien

Reputation: 60402

Read the input in as a string:

std::string input;
std::cin >> input;

Remove the commas, using the erase-remove idiom:

input.erase(std::remove(input.begin(), input.end(), ','), input.end());

which from C++20 you can write like this:

std::erase(input, ',');  // C++20

Convert the string to an int:

int player_input = std::stoi(input);

Upvotes: 2

Related Questions