Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何允许逗号用于基于整数的输入c++;? 我对C++很陌生,我正在尝试编写一个程序,它根据用户输入打印出数字。但是,当您添加一个,时,它会中断代码,因为它不是整数的一部分。我该怎么办_C++ - Fatal编程技术网

如何允许逗号用于基于整数的输入c++;? 我对C++很陌生,我正在尝试编写一个程序,它根据用户输入打印出数字。但是,当您添加一个,时,它会中断代码,因为它不是整数的一部分。我该怎么办

如何允许逗号用于基于整数的输入c++;? 我对C++很陌生,我正在尝试编写一个程序,它根据用户输入打印出数字。但是,当您添加一个,时,它会中断代码,因为它不是整数的一部分。我该怎么办,c++,C++,我制作了一个简化的代码,因为我想对整数做更多的处理: #include <iostream> using namespace std; int main(){ int player_input; cout << "Insert the number" << endl; cin >> player_input; cout << player_input; return 0;

我制作了一个简化的代码,因为我想对整数做更多的处理:

#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"
}
#包括
使用名称空间std;
int main(){
int-player_输入;
不能输入;

无法将输入作为字符串读入:

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

使用擦除-删除习惯用法删除逗号:

input.erase(std::remove(input.begin(), input.end(), ','), input.end());
从C++20中可以这样编写:

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

将字符串转换为int:

int player_input = std::stoi(input);
使用
,您可以执行以下操作:

#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;
    // ...
}
#包括
模板类千分位分隔符:public std::numpunct{
公众:
千位分隔符(T分隔符):m_分隔符(分隔符){}
受保护的:
T do_sep()常量重写{return m_Separator;}
std::string do_grouping()常量重写{return“\03”;}
私人:
T m_分离器;
};
int main(){
千个平行面(',');
std::cin.imbue(std::locale(std::cin.getloc(),&facet));
int n;
标准:cin>>n;
// ...
}

我认为@Jarod42的总体思路是正确的,但我认为通常没有很好的理由为此任务定义您自己的区域设置。在大多数情况下,您需要使用预定义的区域设置来完成此任务。例如,以下代码:

#包括
#包括
int main(){
标准::cin.imbue(标准::地区(“美国”);
int i;
标准:cin>>i;

std::cout显然(?)您必须停止读取整数,因为逗号不能是整数的一部分。相反,您应该读取字符串(逗号可以是字符串的一部分)然后编写代码将包含数字和逗号的字符串转换为整数。对于初学者来说,这似乎很难。但如果这是你想要的,那就是你必须做的。@iBug否,因为请求不是逗号分隔的整数,而是包含逗号的整数,以便于阅读,例如1000000是一个m百万不是三个独立的整数。