c++ - 忽略 C++ cin 中的逗号

标签 c++ std cin

我有以下代码:

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
cin >> x1;
cin.ignore(1, ',');
cin >> y1;
cin >> x2;
cin.ignore(1, ',');
cin >> y2;
cout << "Coordinates registered as (" << x1 << "," << y1 << "), (" << x2 << "," << y2 << ").\n";

但这总是返回 (0,0) (0,0)。

cin.ignore 的正确实现应该是什么?

最佳答案

如果您以 (x1,y1) (x2,y2) 的形式输入数据,例如

(10,20) (30,40)

然后您将需要使用括号和逗号。一个简单的方法是声明一个 char 变量并使用它来获取需要删除的单个字符

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater; // removes (
std::cin >> x1;
std::cin >> eater; // removes ,
std::cin >> y1;
std::cin >> eater; //removes )
std::cin >> eater; // removes (
std::cin >> x2;
std::cin >> eater; // removes ,
std::cin >> y2;
std::cin >> eater; //removes )

为了让它更紧凑一点,你可以每行获得一个坐标

float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater >> x1 >> eater >> y1 >> eater;
//            (              ,              )
std::cin >> eater >> x2 >> eater >> y2 >> eater;
//            (              ,              )

我喜欢在其中留下评论,以表达每次获得输入时应该消耗什么。

关于c++ - 忽略 C++ cin 中的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33106519/

相关文章:

c++ - 跳过 cin.get() 和 cin.ignore()

c++ - 如何创建我自己的 'cout' 和 'cerr' 类

c++ - 二维数组的静默运行时错误

c++ - 模板构造函数

c++ - 为什么 Visual C++ 编译器将未使用的类编译为可执行文件?

C++ const std::map 引用无法编译

c++ - 未分配正在释放的 Malloc 指针

c++ - 对 int[2] 数组进行排序无法编译

c++ - 尝试从 std::stack 中删除项目时出错

c++ - 无法从 cin.get() 获取字符