我有以下代码:
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/