我有以下代码:
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的正确实现是什么?
答案 0 :(得分:3)
如果您确实以(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;
// ( , )
我希望将评论留在那里,以表达每次获得输入时应该使用的内容。